ng-firebase-table-kxp 1.0.8 → 1.0.9

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.
@@ -35,1980 +35,2082 @@ import * as i1 from '@angular/fire/compat/firestore';
35
35
  import * as i3 from 'ngx-toastr';
36
36
  import * as i12 from '@angular/material/core';
37
37
 
38
- class NgFirebaseTableKxpComponent {
39
- }
40
- NgFirebaseTableKxpComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgFirebaseTableKxpComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
41
- NgFirebaseTableKxpComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.2.10", type: NgFirebaseTableKxpComponent, selector: "lib-ng-firebase-table-kxp", ngImport: i0, template: ` <p>ng-firebase-table-kxp works!</p> `, isInline: true });
42
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgFirebaseTableKxpComponent, decorators: [{
43
- type: Component,
44
- args: [{ selector: 'lib-ng-firebase-table-kxp', template: ` <p>ng-firebase-table-kxp works!</p> ` }]
38
+ class NgFirebaseTableKxpComponent {
39
+ }
40
+ NgFirebaseTableKxpComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgFirebaseTableKxpComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
41
+ NgFirebaseTableKxpComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.2.10", type: NgFirebaseTableKxpComponent, selector: "lib-ng-firebase-table-kxp", ngImport: i0, template: ` <p>ng-firebase-table-kxp works!</p> `, isInline: true });
42
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgFirebaseTableKxpComponent, decorators: [{
43
+ type: Component,
44
+ args: [{ selector: 'lib-ng-firebase-table-kxp', template: ` <p>ng-firebase-table-kxp works!</p> ` }]
45
45
  }] });
46
46
 
47
- class TableService {
48
- constructor(ngFire, dialog, toastr) {
49
- this.ngFire = ngFire;
50
- this.dialog = dialog;
51
- this.toastr = toastr;
52
- this.operators = {
53
- '==': (a, b) => a === b,
54
- '!=': (a, b) => a !== b,
55
- '>': (a, b) => a > b,
56
- '<': (a, b) => a < b,
57
- '>=': (a, b) => a >= b,
58
- '<=': (a, b) => a <= b,
59
- in: (a, b) => Array.isArray(b) && b.includes(a),
60
- 'not-in': (a, b) => Array.isArray(b) && !b.includes(a),
61
- 'array-contains': (a, b) => Array.isArray(a) && a.includes(b),
62
- 'array-contains-any': (a, b) => Array.isArray(a) &&
63
- Array.isArray(b) &&
64
- b.some((item) => a.includes(item)),
65
- includes: (a, b) => a.includes(b), // Para strings ou arrays
66
- };
67
- }
68
- async getItems(collection) {
69
- try {
70
- const querySnapshot = await collection.get();
71
- return querySnapshot.docs.map((doc) => {
72
- return { ...doc.data(), id: doc.id };
73
- });
74
- }
75
- catch (error) {
76
- console.warn('Collection não encontrada:', error);
77
- return [];
78
- }
79
- }
80
- async executeQuery(params) {
81
- if (params.filterFn) {
82
- // Lógica com filtro no cliente (filterFn)
83
- const BATCH_FETCH_SIZE = params.batchSize;
84
- const GOAL_SIZE = params.batchSize + 1;
85
- if (params.navigation === 'forward' || params.navigation === 'reload') {
86
- if (params.navigation === 'reload' && params.doc) {
87
- params.doc.lastDoc = null;
88
- }
89
- let lastDocCursor = params.doc ? params.doc.lastDoc : null;
90
- let pageResults = [];
91
- let allFetchedDocs = [];
92
- let hasMoreDocsInDb = true;
93
- while (pageResults.length < GOAL_SIZE && hasMoreDocsInDb) {
94
- let query = this.ngFire.collection(params.collection).ref;
95
- query = this.applyFilters(query, params.arrange, params.conditions);
96
- if (lastDocCursor) {
97
- query = query.startAfter(lastDocCursor);
98
- }
99
- query = query.limit(BATCH_FETCH_SIZE);
100
- const snapshot = await query.get();
101
- if (snapshot.empty) {
102
- hasMoreDocsInDb = false;
103
- break;
104
- }
105
- lastDocCursor = snapshot.docs[snapshot.docs.length - 1];
106
- allFetchedDocs.push(...snapshot.docs);
107
- const batchUsers = snapshot.docs
108
- .map((doc) => ({
109
- id: doc.id,
110
- ...doc.data(),
111
- }))
112
- .filter(params.filterFn);
113
- pageResults.push(...batchUsers);
114
- if (snapshot.size < BATCH_FETCH_SIZE) {
115
- hasMoreDocsInDb = false;
116
- }
117
- }
118
- const hasNextPage = pageResults.length > params.batchSize;
119
- const finalItems = pageResults.slice(0, params.batchSize);
120
- const firstDocOfPage = allFetchedDocs.find((doc) => doc.id === finalItems[0]?.id) || null;
121
- const lastDocOfPage = allFetchedDocs.find((doc) => doc.id === finalItems[finalItems.length - 1]?.id) || null;
122
- return {
123
- items: finalItems,
124
- filterLength: null,
125
- firstDoc: firstDocOfPage,
126
- lastDoc: lastDocOfPage,
127
- hasNextPage: hasNextPage,
128
- hasPreviousPage: !!(params.doc && params.doc.lastDoc) &&
129
- params.navigation !== 'reload',
130
- currentClientPageIndex: undefined,
131
- };
132
- }
133
- // Lógica para trás (backward)
134
- else if (params.navigation === 'backward') {
135
- if (!params.doc || !params.doc.firstDoc) {
136
- return {
137
- items: [],
138
- filterLength: null,
139
- firstDoc: null,
140
- lastDoc: null,
141
- hasNextPage: true,
142
- hasPreviousPage: false,
143
- currentClientPageIndex: undefined,
144
- };
145
- }
146
- let pageResults = [];
147
- let allFetchedDocs = [];
148
- let hasMoreDocsInDb = true;
149
- let boundaryDoc = params.doc.firstDoc;
150
- while (pageResults.length < GOAL_SIZE && hasMoreDocsInDb) {
151
- let query = this.ngFire.collection(params.collection).ref;
152
- query = this.applyFilters(query, params.arrange, params.conditions);
153
- query = query.endBefore(boundaryDoc);
154
- query = query.limitToLast(BATCH_FETCH_SIZE);
155
- const snapshot = await query.get();
156
- if (snapshot.empty) {
157
- hasMoreDocsInDb = false;
158
- break;
159
- }
160
- boundaryDoc = snapshot.docs[0];
161
- allFetchedDocs = [...snapshot.docs, ...allFetchedDocs];
162
- const batchUsers = snapshot.docs
163
- .map((doc) => ({
164
- id: doc.id,
165
- ...doc.data(),
166
- }))
167
- .filter(params.filterFn);
168
- pageResults = [...batchUsers, ...pageResults];
169
- if (snapshot.size < BATCH_FETCH_SIZE) {
170
- hasMoreDocsInDb = false;
171
- }
172
- }
173
- const finalItems = pageResults.slice(0, params.batchSize);
174
- const firstDocOfPage = allFetchedDocs.find((doc) => doc.id === finalItems[0]?.id) || null;
175
- const lastDocOfPage = allFetchedDocs.find((doc) => doc.id === finalItems[finalItems.length - 1]?.id) || null;
176
- return {
177
- items: finalItems,
178
- filterLength: null,
179
- firstDoc: firstDocOfPage,
180
- lastDoc: lastDocOfPage,
181
- hasNextPage: true,
182
- currentClientPageIndex: undefined,
183
- };
184
- }
185
- }
186
- else {
187
- let items = [];
188
- let docs = [];
189
- let hasNextPage = false;
190
- let filterLength = null;
191
- let query = this.ngFire.collection(params.collection).ref;
192
- if (params.conditions) {
193
- params.conditions.forEach((c) => {
194
- if (c.operator === '!=') {
195
- query = query.orderBy(c.firestoreProperty);
196
- }
197
- });
198
- }
199
- query = this.applyFilters(query, params.arrange, params.conditions);
200
- if (params.navigation === 'reload') {
201
- query = query.limit(params.batchSize + 1);
202
- if (params.doc && params.doc.firstDoc) {
203
- query = query.startAt(params.doc.firstDoc);
204
- }
205
- }
206
- else if (params.navigation === 'forward') {
207
- query = query.limit(params.batchSize + 1);
208
- if (params.doc && params.doc.lastDoc) {
209
- query = query.startAfter(params.doc.lastDoc);
210
- }
211
- }
212
- else {
213
- // backward
214
- query = query.limitToLast(params.batchSize + 1);
215
- if (params.doc && params.doc.firstDoc) {
216
- query = query.endBefore(params.doc.firstDoc);
217
- }
218
- }
219
- const itemCol = await query.get();
220
- itemCol.docs.forEach((doc) => docs.push(doc));
221
- const itemPromises = docs.map(async (item) => {
222
- const itemData = item.data();
223
- items.push({ id: item.id, ...itemData });
224
- });
225
- let lastDoc = docs[docs.length - 1] || null;
226
- let firstDoc = docs[0];
227
- if ((items.length > params.batchSize && params.navigation === 'forward') ||
228
- (params.navigation === 'reload' && items.length > params.batchSize)) {
229
- lastDoc = docs[docs.length - 2] || null;
230
- items.pop();
231
- hasNextPage = true;
232
- }
233
- if (items.length > params.batchSize && params.navigation === 'backward') {
234
- firstDoc = docs[1];
235
- items.shift();
236
- hasNextPage = true;
237
- }
238
- await Promise.all(itemPromises);
239
- return {
240
- items,
241
- filterLength,
242
- lastDoc,
243
- firstDoc,
244
- hasNextPage,
245
- currentClientPageIndex: undefined,
246
- };
247
- }
248
- // Fallback para garantir que sempre retornamos algo
249
- return {
250
- items: [],
251
- filterLength: null,
252
- firstDoc: null,
253
- lastDoc: null,
254
- hasNextPage: false,
255
- currentClientPageIndex: undefined,
256
- };
257
- }
258
- applyFilters(query, arrange, conditions) {
259
- if (conditions) {
260
- conditions.map((cond) => {
261
- query = query.where(cond.firestoreProperty, cond.operator, cond.dashProperty);
262
- });
263
- }
264
- let hasFilterSpecificOrderBy = false;
265
- let appliedOrderByField = null;
266
- const equalsFilters = arrange.filters.filter((f) => f.arrange === 'equals' && f.filter);
267
- const otherFilters = arrange.filters.filter((f) => f.arrange !== 'equals');
268
- const equalsGroupedByProperty = equalsFilters.reduce((acc, current) => {
269
- const prop = current.filter.property;
270
- if (!acc[prop]) {
271
- acc[prop] = [];
272
- }
273
- acc[prop].push(current.filter.filtering);
274
- return acc;
275
- }, {});
276
- for (const prop in equalsGroupedByProperty) {
277
- const values = equalsGroupedByProperty[prop];
278
- if (values.length > 0) {
279
- query = query.where(prop, 'in', values);
280
- }
281
- }
282
- otherFilters.forEach((filterItem) => {
283
- // Aplicar filtragem por busca
284
- if (filterItem.filter?.filtering &&
285
- filterItem.filter?.property !== '' &&
286
- filterItem.arrange === 'filter') {
287
- query = query
288
- .where(filterItem.filter.property, '>=', filterItem.filter.filtering.trim().toUpperCase())
289
- .where(filterItem.filter.property, '<=', filterItem.filter.filtering.trim().toUpperCase() + '\uf8ff');
290
- if (!hasFilterSpecificOrderBy) {
291
- query = query.orderBy(filterItem.filter.property);
292
- hasFilterSpecificOrderBy = true;
293
- appliedOrderByField = filterItem.filter.property;
294
- }
295
- }
296
- // Aplicar filtro do tipo "filterByDate"
297
- if (filterItem.dateFilter && filterItem.arrange === 'filterByDate') {
298
- query = query
299
- .where(arrange.sortBy.field, '>=', filterItem.dateFilter.initial)
300
- .where(arrange.sortBy.field, '<=', filterItem.dateFilter.final);
301
- if (!hasFilterSpecificOrderBy) {
302
- query = query.orderBy(arrange.sortBy.field);
303
- hasFilterSpecificOrderBy = true;
304
- appliedOrderByField = arrange.sortBy.field;
305
- }
306
- }
307
- });
308
- // Aplicar sortBy
309
- if (arrange.sortBy && arrange.sortBy.field && arrange.sortBy.order) {
310
- if (appliedOrderByField !== arrange.sortBy.field) {
311
- query = query.orderBy(arrange.sortBy.field, arrange.sortBy.order);
312
- }
313
- }
314
- return query;
315
- }
316
- getIdFilter(params) {
317
- if (!params.arrange?.filters)
318
- return null;
319
- const idFilter = params.arrange.filters.find((f) => f.arrange === 'filter' &&
320
- f.filter?.property === 'id' &&
321
- f.filter?.filtering);
322
- return idFilter?.filter?.filtering?.trim() || null;
323
- }
324
- async getDocumentById(collection, docId) {
325
- try {
326
- const docRef = this.ngFire.collection(collection).doc(docId);
327
- const docSnapshot = await docRef.get().toPromise();
328
- if (docSnapshot && docSnapshot.exists) {
329
- return {
330
- id: docSnapshot.id,
331
- ...docSnapshot.data(),
332
- };
333
- }
334
- return null;
335
- }
336
- catch (error) {
337
- console.warn('Erro ao buscar documento por ID:', error);
338
- return null;
339
- }
340
- }
341
- async searchByIdPartial(params, searchTerm) {
342
- const exactMatch = await this.getDocumentById(params.collection, searchTerm);
343
- if (exactMatch) {
344
- if (params.conditions) {
345
- const operators = this.operators;
346
- const passesConditions = params.conditions.every((cond) => {
347
- const operatorFn = operators[cond.operator];
348
- return operatorFn
349
- ? operatorFn(exactMatch[cond.firestoreProperty], cond.dashProperty)
350
- : false;
351
- });
352
- if (!passesConditions) {
353
- return {
354
- items: [],
355
- filterLength: 0,
356
- firstDoc: null,
357
- lastDoc: null,
358
- hasNextPage: false,
359
- hasPreviousPage: false,
360
- currentClientPageIndex: 0,
361
- totalPages: 0,
362
- };
363
- }
364
- }
365
- if (params.filterFn && !params.filterFn(exactMatch)) {
366
- return {
367
- items: [],
368
- filterLength: 0,
369
- firstDoc: null,
370
- lastDoc: null,
371
- hasNextPage: false,
372
- hasPreviousPage: false,
373
- currentClientPageIndex: 0,
374
- totalPages: 0,
375
- };
376
- }
377
- return {
378
- items: [exactMatch],
379
- filterLength: 1,
380
- firstDoc: null,
381
- lastDoc: null,
382
- hasNextPage: false,
383
- hasPreviousPage: false,
384
- currentClientPageIndex: 0,
385
- totalPages: 1,
386
- };
387
- }
388
- const searchTermLower = searchTerm.toLowerCase();
389
- const paramsWithoutIdFilter = {
390
- ...params,
391
- arrange: {
392
- ...params.arrange,
393
- filters: params.arrange.filters.filter((f) => !(f.arrange === 'filter' && f.filter?.property === 'id')),
394
- },
395
- };
396
- let query = this.ngFire.collection(params.collection).ref;
397
- // Aplicar conditions
398
- if (params.conditions) {
399
- params.conditions.forEach((cond) => {
400
- query = query.where(cond.firestoreProperty, cond.operator, cond.dashProperty);
401
- });
402
- }
403
- // Aplicar sortBy
404
- if (params.arrange?.sortBy?.field && params.arrange?.sortBy?.order) {
405
- query = query.orderBy(params.arrange.sortBy.field, params.arrange.sortBy.order);
406
- }
407
- const snapshot = await query.get();
408
- let items = snapshot.docs
409
- .map((doc) => ({
410
- id: doc.id,
411
- ...doc.data(),
412
- }))
413
- .filter((item) => item.id.toLowerCase().includes(searchTermLower));
414
- // Separar equals filters e outros filtros
415
- const equalsFilters = paramsWithoutIdFilter.arrange.filters.filter((f) => f.arrange === 'equals' && f.filter);
416
- const otherFilters = paramsWithoutIdFilter.arrange.filters.filter((f) => f.arrange !== 'equals' &&
417
- (f.arrange !== 'filter' || f.filter?.property !== 'id'));
418
- // Aplicar equals filters com lógica OR dentro de cada propriedade
419
- if (equalsFilters.length > 0) {
420
- // Agrupar por propriedade para aplicar OR
421
- const groupedByProperty = equalsFilters.reduce((acc, f) => {
422
- const prop = f.filter.property;
423
- if (!acc[prop]) {
424
- acc[prop] = [];
425
- }
426
- acc[prop].push(f.filter.filtering);
427
- return acc;
428
- }, {});
429
- // Filtrar: item deve ter pelo menos um valor de CADA propriedade
430
- items = items.filter((item) => {
431
- return Object.entries(groupedByProperty).every(([prop, values]) => {
432
- return values.includes(item[prop]);
433
- });
434
- });
435
- }
436
- // Aplicar outros filtros
437
- otherFilters.forEach((filterItem) => {
438
- if (filterItem.arrange === 'filter' &&
439
- filterItem.filter?.filtering &&
440
- filterItem.filter?.property) {
441
- const filterValue = String(filterItem.filter.filtering)
442
- .trim()
443
- .toLowerCase();
444
- items = items.filter((item) => {
445
- const itemValue = String(item[filterItem.filter.property]).toLowerCase();
446
- return itemValue.includes(filterValue);
447
- });
448
- }
449
- });
450
- // Aplicar filterFn se existir
451
- if (params.filterFn) {
452
- items = items.filter(params.filterFn);
453
- }
454
- // Paginação
455
- const pageSize = params.batchSize;
456
- let currentClientPageIndex = 0;
457
- if (params.navigation === 'reload') {
458
- currentClientPageIndex = 0;
459
- }
460
- else {
461
- // Usar o índice passado pelo componente sem incrementar/decrementar
462
- currentClientPageIndex = params.clientPageIndex || 0;
463
- }
464
- const startIndex = currentClientPageIndex * pageSize;
465
- const endIndex = startIndex + pageSize;
466
- const paginatedItems = items.slice(startIndex, endIndex);
467
- const totalPages = Math.ceil(items.length / pageSize);
468
- const hasNextPage = currentClientPageIndex < totalPages - 1;
469
- const hasPreviousPage = currentClientPageIndex > 0;
470
- return {
471
- items: paginatedItems,
472
- filterLength: items.length,
473
- firstDoc: null,
474
- lastDoc: null,
475
- hasNextPage,
476
- hasPreviousPage,
477
- currentClientPageIndex,
478
- totalPages,
479
- };
480
- }
481
- shouldUseClientSideFallback(params) {
482
- const hasConditions = params.conditions && params.conditions.length > 0;
483
- const hasArrangeFilters = params.arrange?.filters && params.arrange.filters.length > 0;
484
- const hasSortBy = params.arrange?.sortBy?.field;
485
- if (params.filterFn) {
486
- return false;
487
- }
488
- if (hasArrangeFilters) {
489
- const equalsFilters = params.arrange.filters.filter((f) => f.arrange === 'equals' && f.filter);
490
- if (equalsFilters.length > 0) {
491
- const propertiesSet = new Set(equalsFilters.map((f) => f.filter.property));
492
- if (propertiesSet.size > 1) {
493
- return true;
494
- }
495
- }
496
- }
497
- if (hasConditions && hasArrangeFilters && hasSortBy) {
498
- return true;
499
- }
500
- if (hasConditions && hasArrangeFilters) {
501
- return true;
502
- }
503
- if (hasArrangeFilters && params.arrange.filters.length > 1 && hasSortBy) {
504
- const equalsFilters = params.arrange.filters.filter((f) => f.arrange === 'equals' && f.filter);
505
- if (equalsFilters.length > 0) {
506
- const propertiesSet = new Set(equalsFilters.map((f) => f.filter.property));
507
- if (propertiesSet.size === 1 &&
508
- equalsFilters.length === params.arrange.filters.length) {
509
- return false;
510
- }
511
- }
512
- return true;
513
- }
514
- return false;
515
- }
516
- async getPaginated(params) {
517
- const idFilterValue = this.getIdFilter(params);
518
- if (idFilterValue) {
519
- const result = await this.searchByIdPartial(params, idFilterValue);
520
- return result;
521
- }
522
- // Detectar preventivamente se deve usar fallback
523
- if (this.shouldUseClientSideFallback(params)) {
524
- await this.trackMissingIndexPreventive(params.collection, params.arrange, params.conditions);
525
- const result = await this.executeClientSideQuery(params);
526
- console.log('📊 [TABLE] Resultados paginados via fallback client-side:', {
527
- totalItems: result.filterLength,
528
- returnedItems: result.items.length,
529
- hasNextPage: result.hasNextPage,
530
- currentPage: (result.currentClientPageIndex || 0) + 1,
531
- });
532
- return result;
533
- }
534
- try {
535
- const result = await this.executeQuery(params);
536
- console.log('📊 [TABLE] Resultados paginados via Firestore:', {
537
- totalItems: result.filterLength || 'N/A',
538
- returnedItems: result.items.length,
539
- hasNextPage: result.hasNextPage,
540
- });
541
- return result;
542
- }
543
- catch (error) {
544
- if (error && error.code === 'failed-precondition') {
545
- await this.trackMissingIndex(error, params.collection, params.arrange, params.conditions);
546
- const result = await this.executeClientSideQuery(params);
547
- console.log('📊 [TABLE] Resultados paginados via fallback (erro de index):', {
548
- totalItems: result.filterLength,
549
- returnedItems: result.items.length,
550
- hasNextPage: result.hasNextPage,
551
- currentPage: (result.currentClientPageIndex || 0) + 1,
552
- });
553
- return result;
554
- }
555
- else if (error && error.code === 'invalid-argument') {
556
- await this.trackMissingIndex(error, params.collection, params.arrange, params.conditions);
557
- const result = await this.executeClientSideQuery(params);
558
- console.log('📊 [TABLE] Resultados paginados via fallback (argumento inválido):', {
559
- totalItems: result.filterLength,
560
- returnedItems: result.items.length,
561
- hasNextPage: result.hasNextPage,
562
- currentPage: (result.currentClientPageIndex || 0) + 1,
563
- });
564
- return result;
565
- }
566
- else {
567
- throw error;
568
- }
569
- }
570
- }
571
- async executeClientSideQuery(params) {
572
- // Otimizar usando pelo menos uma cláusula .where() quando possível
573
- let query = this.ngFire.collection(params.collection).ref;
574
- let appliedCondition = null;
575
- let hasAppliedWhereClause = false;
576
- // Primeiro, tenta aplicar condições simples
577
- if (params.conditions && params.conditions.length > 0) {
578
- const simpleCondition = params.conditions.find((cond) => ['==', '>', '<', '>=', '<=', 'in', 'array-contains'].includes(cond.operator));
579
- if (simpleCondition) {
580
- query = query.where(simpleCondition.firestoreProperty, simpleCondition.operator, simpleCondition.dashProperty);
581
- appliedCondition = simpleCondition;
582
- hasAppliedWhereClause = true;
583
- }
584
- }
585
- // Se não há condições disponíveis, tenta aplicar filtros do arrange
586
- let appliedFirestoreFilter = null;
587
- if (!hasAppliedWhereClause && params.arrange?.filters) {
588
- // Agrupar equals filters por propriedade
589
- const equalsFilters = params.arrange.filters.filter((f) => f.arrange === 'equals' && f.filter);
590
- const equalsGroupedByProperty = equalsFilters.reduce((acc, current) => {
591
- const prop = current.filter.property;
592
- if (!acc[prop]) {
593
- acc[prop] = [];
594
- }
595
- acc[prop].push(current.filter.filtering);
596
- return acc;
597
- }, {});
598
- // Se há apenas UMA propriedade com múltiplos valores, aplicar no Firestore com 'in'
599
- const properties = Object.keys(equalsGroupedByProperty);
600
- if (properties.length === 1 && equalsFilters.length > 0) {
601
- const prop = properties[0];
602
- const values = equalsGroupedByProperty[prop];
603
- query = query.where(prop, 'in', values);
604
- hasAppliedWhereClause = true;
605
- // Marcar TODOS os equals filters dessa propriedade como aplicados
606
- appliedFirestoreFilter = 'all-equals';
607
- }
608
- else if (properties.length === 0) {
609
- const otherFilter = params.arrange.filters.find((f) => (f.arrange === 'filter' &&
610
- f.filter?.filtering &&
611
- f.filter?.property) ||
612
- (f.arrange === 'filterByDate' &&
613
- f.dateFilter?.initial &&
614
- f.dateFilter?.final));
615
- if (otherFilter) {
616
- if (otherFilter.arrange === 'filter' && otherFilter.filter) {
617
- const filterValue = otherFilter.filter.filtering
618
- .trim()
619
- .toUpperCase();
620
- query = query
621
- .where(otherFilter.filter.property, '>=', filterValue)
622
- .where(otherFilter.filter.property, '<=', filterValue + '\uf8ff');
623
- hasAppliedWhereClause = true;
624
- appliedFirestoreFilter = otherFilter;
625
- }
626
- else if (otherFilter.arrange === 'filterByDate' &&
627
- otherFilter.dateFilter &&
628
- params.arrange.sortBy?.field) {
629
- query = query
630
- .where(params.arrange.sortBy.field, '>=', otherFilter.dateFilter.initial)
631
- .where(params.arrange.sortBy.field, '<=', otherFilter.dateFilter.final);
632
- hasAppliedWhereClause = true;
633
- appliedFirestoreFilter = otherFilter;
634
- }
635
- }
636
- }
637
- }
638
- const allDocsSnapshot = await query.get();
639
- let items = allDocsSnapshot.docs.map((doc) => ({
640
- id: doc.id,
641
- ...doc.data(),
642
- }));
643
- // Aplicar condições restantes
644
- if (params.conditions) {
645
- const remainingConditions = params.conditions.filter((cond) => cond !== appliedCondition);
646
- if (remainingConditions.length > 0) {
647
- const operators = this.operators;
648
- items = items.filter((item) => {
649
- return remainingConditions.every((cond) => {
650
- const operatorFn = operators[cond.operator];
651
- return operatorFn
652
- ? operatorFn(item[cond.firestoreProperty], cond.dashProperty)
653
- : false;
654
- });
655
- });
656
- }
657
- }
658
- const { filters, sortBy } = params.arrange;
659
- // Track which filter was already applied in Firestore to avoid double filtering
660
- if (hasAppliedWhereClause && !appliedCondition && params.arrange?.filters) {
661
- const equalsFilter = params.arrange.filters.find((f) => f.arrange === 'equals' && f.filter?.filtering);
662
- if (equalsFilter) {
663
- appliedFirestoreFilter = equalsFilter;
664
- }
665
- else {
666
- appliedFirestoreFilter = params.arrange.filters.find((f) => (f.arrange === 'filter' &&
667
- f.filter?.filtering &&
668
- f.filter?.property) ||
669
- (f.arrange === 'filterByDate' &&
670
- f.dateFilter?.initial &&
671
- f.dateFilter?.final));
672
- }
673
- }
674
- const equalsFilters = filters.filter((f) => f.arrange === 'equals');
675
- const otherFilters = filters.filter((f) => f.arrange !== 'equals');
676
- // Aplicar equals filters no client-side apenas se não foram aplicados no Firestore
677
- if (appliedFirestoreFilter !== 'all-equals' && equalsFilters.length > 0) {
678
- // Agrupar por propriedade para aplicar OR dentro de cada propriedade
679
- const groupedByProperty = equalsFilters.reduce((acc, f) => {
680
- const prop = f.filter.property;
681
- if (!acc[prop]) {
682
- acc[prop] = [];
683
- }
684
- acc[prop].push(f.filter.filtering);
685
- return acc;
686
- }, {});
687
- // Filtrar: item deve ter pelo menos um valor de CADA propriedade
688
- // (AND entre propriedades, OR dentro de cada propriedade)
689
- items = items.filter((item) => {
690
- return Object.entries(groupedByProperty).every(([prop, values]) => {
691
- return values.includes(item[prop]);
692
- });
693
- });
694
- }
695
- otherFilters.forEach((filterItem) => {
696
- if (appliedFirestoreFilter === filterItem) {
697
- return;
698
- }
699
- if (filterItem.arrange === 'filter' &&
700
- filterItem.filter?.filtering &&
701
- filterItem.filter?.property) {
702
- const filterValue = String(filterItem.filter.filtering)
703
- .trim()
704
- .toLowerCase();
705
- items = items.filter((item) => {
706
- const itemValue = String(item[filterItem.filter.property]).toLowerCase();
707
- return itemValue.includes(filterValue);
708
- });
709
- }
710
- if (filterItem.arrange === 'filterByDate' &&
711
- filterItem.dateFilter?.initial &&
712
- filterItem.dateFilter?.final &&
713
- sortBy.field) {
714
- items = items.filter((item) => {
715
- try {
716
- const fieldValue = item[sortBy.field];
717
- if (!fieldValue) {
718
- return false;
719
- }
720
- let itemDate;
721
- if (typeof fieldValue.toDate === 'function') {
722
- itemDate = fieldValue.toDate();
723
- }
724
- else if (fieldValue instanceof Date) {
725
- itemDate = fieldValue;
726
- }
727
- else if (typeof fieldValue === 'string') {
728
- itemDate = new Date(fieldValue);
729
- if (isNaN(itemDate.getTime())) {
730
- return false;
731
- }
732
- }
733
- else if (typeof fieldValue === 'number') {
734
- itemDate = new Date(fieldValue);
735
- }
736
- else {
737
- return false;
738
- }
739
- return (itemDate >= filterItem.dateFilter.initial &&
740
- itemDate <= filterItem.dateFilter.final);
741
- }
742
- catch (error) {
743
- console.warn('Erro ao processar filtro de data para o item:', item.id, error);
744
- return false;
745
- }
746
- });
747
- }
748
- });
749
- // Aplicar filterFn se existir
750
- if (params.filterFn) {
751
- items = items.filter(params.filterFn);
752
- }
753
- if (sortBy && sortBy.field && sortBy.order) {
754
- items.sort((a, b) => {
755
- const valA = a[sortBy.field];
756
- const valB = b[sortBy.field];
757
- if (valA < valB) {
758
- return sortBy.order === 'asc' ? -1 : 1;
759
- }
760
- if (valA > valB) {
761
- return sortBy.order === 'asc' ? 1 : -1;
762
- }
763
- return 0;
764
- });
765
- }
766
- // Implementação adequada da paginação
767
- let currentClientPageIndex = 0;
768
- // Determinar a página atual baseada na navegação
769
- if (params.navigation === 'reload') {
770
- currentClientPageIndex = 0;
771
- }
772
- else {
773
- currentClientPageIndex = params.clientPageIndex || 0;
774
- }
775
- const pageSize = params.batchSize;
776
- const startIndex = currentClientPageIndex * pageSize;
777
- const endIndex = startIndex + pageSize;
778
- const paginatedItems = items.slice(startIndex, endIndex);
779
- const totalPages = Math.ceil(items.length / pageSize);
780
- const hasNextPage = currentClientPageIndex < totalPages - 1;
781
- const hasPreviousPage = currentClientPageIndex > 0;
782
- return {
783
- items: paginatedItems,
784
- filterLength: items.length,
785
- lastDoc: null,
786
- firstDoc: null,
787
- hasNextPage: hasNextPage,
788
- hasPreviousPage: hasPreviousPage,
789
- currentClientPageIndex: currentClientPageIndex,
790
- totalPages: totalPages,
791
- };
792
- }
793
- async getItemsData(collection, arrange, conditions = undefined) {
794
- try {
795
- let query = this.ngFire.collection(collection).ref;
796
- query = this.applyFilters(query, arrange, conditions);
797
- const snapshot = await query.get();
798
- return await Promise.all(snapshot.docs.map(async (doc) => {
799
- const data = doc.data();
800
- const id = doc.id;
801
- return {
802
- id,
803
- ...data,
804
- };
805
- }));
806
- }
807
- catch (e) {
808
- throw e;
809
- }
810
- }
811
- async deleteIndex(id, col) {
812
- try {
813
- const batch = this.ngFire.firestore.batch();
814
- const docRef = this.ngFire.collection(col).doc(id);
815
- const docSnapshot = (await firstValueFrom(docRef.get()));
816
- const doc = docSnapshot.data();
817
- batch.delete(docRef.ref);
818
- if (doc && typeof doc.index === 'number') {
819
- await this.reindex(doc.index, col, batch);
820
- }
821
- await batch.commit();
822
- this.toastr.success('Item excluído com sucesso!');
823
- return true;
824
- }
825
- catch (e) {
826
- const error = e;
827
- console.error('Erro ao deletar item:', error);
828
- this.toastr.error('Erro ao deletar item.');
829
- return false;
830
- }
831
- }
832
- async reindex(index, col, batch) {
833
- try {
834
- const snapshot = (await firstValueFrom(this.ngFire.collection(col).get()));
835
- const docs = snapshot.docs;
836
- for (let doc of docs) {
837
- const data = doc.data();
838
- if (data && typeof data.index === 'number' && data.index > index) {
839
- data.index--;
840
- const docRef = this.ngFire.collection(col).doc(doc.id).ref;
841
- batch.update(docRef, data);
842
- }
843
- }
844
- }
845
- catch (error) {
846
- console.error('Erro ao reindexar:', error);
847
- }
848
- return;
849
- }
850
- dateFormatValidator() {
851
- return (control) => {
852
- if (!control.value) {
853
- return null;
854
- }
855
- const dateStr = control.value.trim();
856
- const datePattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
857
- if (!datePattern.test(dateStr)) {
858
- return { invalidFormat: true };
859
- }
860
- const parts = dateStr.split('/');
861
- const day = parts[0].padStart(2, '0');
862
- const month = parts[1].padStart(2, '0');
863
- const year = parts[2];
864
- const normalizedDate = `${day}/${month}/${year}`;
865
- const date = moment(normalizedDate, 'DD/MM/YYYY', true);
866
- if (!date.isValid()) {
867
- return { invalidDate: true };
868
- }
869
- return null;
870
- };
871
- }
872
- async updateIndex(index, id, col) {
873
- await this.ngFire.collection(col).doc(id).update({ index });
874
- }
875
- /**
876
- * Extrai o link de criação de índice da mensagem de erro do Firestore
877
- */
878
- extractIndexLink(error) {
879
- if (!error || !error.message)
880
- return null;
881
- const linkMatch = error.message.match(/(https:\/\/console\.firebase\.google\.com\/[^\s]+)/);
882
- return linkMatch ? linkMatch[1] : null;
883
- }
884
- /**
885
- * Rastreia índices ausentes ao usar fallback preventivo
886
- */
887
- async trackMissingIndexPreventive(collection, arrange, conditions = undefined) {
888
- try {
889
- const querySignature = this.generateQuerySignature(collection, arrange, conditions);
890
- const docId = `${collection}_${querySignature}`;
891
- const indexLink = this.generateIndexLink(collection, arrange, conditions);
892
- const indexInstructions = this.generateIndexInstructions(collection, arrange, conditions);
893
- const trackingData = {
894
- collection,
895
- indexLink,
896
- indexInstructions,
897
- arrange: {
898
- sortBy: arrange.sortBy,
899
- filters: arrange.filters?.map((f) => ({
900
- arrange: f.arrange,
901
- property: f.filter?.property || null,
902
- dateField: f.arrange === 'filterByDate' ? arrange.sortBy?.field : null,
903
- })) || [],
904
- },
905
- conditions: conditions?.map((c) => ({
906
- property: c.firestoreProperty,
907
- operator: c.operator,
908
- })) || [],
909
- errorMessage: `Fallback preventivo usado para a collection ${collection}. A query exigiria índice composto.`,
910
- updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
911
- };
912
- console.log('📄 [INDEX LINK] Dados que serão salvos no documento:', {
913
- docId,
914
- collection: trackingData.collection,
915
- indexLink: trackingData.indexLink,
916
- arrange: trackingData.arrange,
917
- conditions: trackingData.conditions,
918
- errorMessage: trackingData.errorMessage,
919
- });
920
- const docRef = this.ngFire.collection('missingIndexes').doc(docId);
921
- const doc = await docRef.get().toPromise();
922
- if (doc && doc.exists) {
923
- await docRef.update({
924
- count: firebase.firestore.FieldValue.increment(1),
925
- updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
926
- lastError: trackingData.errorMessage,
927
- });
928
- }
929
- else {
930
- await docRef.set({
931
- ...trackingData,
932
- count: 1,
933
- createdAt: firebase.firestore.FieldValue.serverTimestamp(),
934
- });
935
- }
936
- }
937
- catch (trackingError) {
938
- console.warn('Falha ao rastrear fallback preventivo:', trackingError);
939
- }
940
- }
941
- /**
942
- * Gera uma assinatura única para uma query
943
- */
944
- generateQuerySignature(collection, arrange, conditions = undefined) {
945
- const signature = {
946
- collection,
947
- sortBy: arrange.sortBy,
948
- filters: arrange.filters?.map((f) => ({
949
- arrange: f.arrange,
950
- property: f.filter?.property || null,
951
- })) || [],
952
- conditions: conditions?.map((c) => ({
953
- property: c.firestoreProperty,
954
- operator: c.operator,
955
- })) || [],
956
- };
957
- return btoa(JSON.stringify(signature))
958
- .replace(/[^a-zA-Z0-9]/g, '')
959
- .substring(0, 20);
960
- }
961
- /**
962
- * Gera instruções claras para criar o índice manualmente
963
- */
964
- generateIndexInstructions(collection, arrange, conditions = undefined) {
965
- const instructions = {
966
- summary: '',
967
- collection: collection,
968
- fields: [],
969
- queryExample: '',
970
- stepByStep: [],
971
- notes: [],
972
- };
973
- const fields = [];
974
- if (conditions && conditions.length > 0) {
975
- conditions.forEach((condition) => {
976
- if (condition.firestoreProperty) {
977
- fields.push({
978
- field: condition.firestoreProperty,
979
- order: 'Ascending',
980
- type: 'WHERE clause',
981
- operator: condition.operator,
982
- description: `Filtrar por ${condition.firestoreProperty} usando operador ${condition.operator}`,
983
- });
984
- }
985
- });
986
- }
987
- if (arrange.filters && arrange.filters.length > 0) {
988
- arrange.filters.forEach((filter) => {
989
- if (filter.filter?.property) {
990
- fields.push({
991
- field: filter.filter.property,
992
- order: 'Ascending',
993
- type: 'WHERE clause (filter)',
994
- operator: filter.arrange === 'filter' ? 'CONTAINS' : 'RANGE',
995
- description: `Filtrar por ${filter.filter.property} usando filtro ${filter.arrange}`,
996
- });
997
- }
998
- });
999
- }
1000
- if (arrange.sortBy?.field) {
1001
- fields.push({
1002
- field: arrange.sortBy.field,
1003
- order: arrange.sortBy.order === 'desc' ? 'Descending' : 'Ascending',
1004
- type: 'ORDER BY clause',
1005
- operator: 'N/A',
1006
- description: `Ordenar resultados por ${arrange.sortBy.field} em ordem ${arrange.sortBy.order}`,
1007
- });
1008
- }
1009
- instructions.fields = fields;
1010
- const fieldNames = fields.map((f) => f.field).join(' + ');
1011
- instructions.summary = `Criar índice composto para ${collection}: ${fieldNames}`;
1012
- let queryExample = `db.collection('${collection}')`;
1013
- fields.forEach((field, index) => {
1014
- if (field.type.includes('WHERE')) {
1015
- if (field.operator === '==') {
1016
- queryExample += `\n .where('${field.field}', '==', 'value')`;
1017
- }
1018
- else if (field.operator === 'CONTAINS') {
1019
- queryExample += `\n .where('${field.field}', '>=', 'searchText')`;
1020
- }
1021
- else {
1022
- queryExample += `\n .where('${field.field}', '${field.operator}', 'value')`;
1023
- }
1024
- }
1025
- });
1026
- const orderByField = fields.find((f) => f.type.includes('ORDER BY'));
1027
- if (orderByField) {
1028
- queryExample += `\n .orderBy('${orderByField.field}', '${orderByField.order.toLowerCase()}')`;
1029
- }
1030
- instructions.queryExample = queryExample;
1031
- instructions.stepByStep = [
1032
- '1. Ir para Firebase Console → Firestore → Indexes',
1033
- '2. Clicar em "Create Index"',
1034
- `3. Definir Collection ID: ${collection}`,
1035
- '4. Configurar campos nesta ORDEM EXATA:',
1036
- ...fields.map((field, index) => ` ${index + 1}. Campo: ${field.field}, Order: ${field.order}, Array: No`),
1037
- '5. Definir Query scopes: Collection',
1038
- '6. Clicar em "Create" e aguardar conclusão',
1039
- ];
1040
- instructions.notes = [
1041
- '⚠️ A ordem dos campos é CRÍTICA - deve corresponder exatamente à ordem da query',
1042
- '⚠️ As cláusulas WHERE devem vir ANTES do campo ORDER BY',
1043
- '⚠️ Este índice só funcionará para queries com esta combinação EXATA de campos',
1044
- '⚠️ A criação do índice pode levar vários minutos',
1045
- ];
1046
- return instructions;
1047
- }
1048
- /**
1049
- * Gera um link de índice baseado na estrutura da query
1050
- */
1051
- generateIndexLink(collection, arrange, conditions = undefined) {
1052
- try {
1053
- const indexFields = [];
1054
- if (conditions && conditions.length > 0) {
1055
- conditions.forEach((condition) => {
1056
- if (condition.firestoreProperty) {
1057
- indexFields.push(condition.firestoreProperty);
1058
- }
1059
- });
1060
- }
1061
- if (arrange.filters && arrange.filters.length > 0) {
1062
- arrange.filters.forEach((filter) => {
1063
- if (filter.filter?.property) {
1064
- indexFields.push(filter.filter.property);
1065
- }
1066
- });
1067
- }
1068
- if (arrange.sortBy?.field) {
1069
- indexFields.push(arrange.sortBy.field);
1070
- }
1071
- if (indexFields.length > 1) {
1072
- const baseUrl = 'https://console.firebase.google.com/project/toppayy-dev/firestore/indexes';
1073
- const queryParams = new URLSearchParams({
1074
- create_composite: `collection=${collection}&fields=${indexFields.join(',')}`,
1075
- });
1076
- const finalLink = `${baseUrl}?${queryParams.toString()}`;
1077
- return finalLink;
1078
- }
1079
- return null;
1080
- }
1081
- catch (error) {
1082
- console.warn('Falha ao gerar link de índice:', error);
1083
- return null;
1084
- }
1085
- }
1086
- async trackMissingIndex(error, collection, arrange, conditions = undefined) {
1087
- try {
1088
- const indexLink = this.extractIndexLink(error);
1089
- if (!indexLink)
1090
- return;
1091
- const linkHash = btoa(indexLink)
1092
- .replace(/[^a-zA-Z0-9]/g, '')
1093
- .substring(0, 20);
1094
- const docId = `${collection}_${linkHash}`;
1095
- const indexInstructions = this.generateIndexInstructions(collection, arrange, conditions);
1096
- const trackingData = {
1097
- collection,
1098
- indexLink,
1099
- indexInstructions,
1100
- arrange: {
1101
- sortBy: arrange.sortBy,
1102
- filters: arrange.filters?.map((f) => ({
1103
- arrange: f.arrange,
1104
- property: f.filter?.property || null,
1105
- dateField: f.arrange === 'filterByDate' ? arrange.sortBy?.field : null,
1106
- })) || [],
1107
- },
1108
- conditions: conditions?.map((c) => ({
1109
- property: c.firestoreProperty,
1110
- operator: c.operator,
1111
- })) || [],
1112
- errorMessage: error.message,
1113
- updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
1114
- };
1115
- const docRef = this.ngFire.collection('missingIndexes').doc(docId);
1116
- const doc = await docRef.get().toPromise();
1117
- if (doc && doc.exists) {
1118
- await docRef.update({
1119
- count: firebase.firestore.FieldValue.increment(1),
1120
- updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
1121
- lastError: error.message,
1122
- });
1123
- }
1124
- else {
1125
- await docRef.set({
1126
- ...trackingData,
1127
- count: 1,
1128
- createdAt: firebase.firestore.FieldValue.serverTimestamp(),
1129
- });
1130
- }
1131
- }
1132
- catch (trackingError) {
1133
- console.warn('Falha ao rastrear índice ausente:', trackingError);
1134
- }
1135
- }
1136
- }
1137
- TableService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: TableService, deps: [{ token: i1.AngularFirestore, optional: true }, { token: i2.MatDialog, optional: true }, { token: i3.ToastrService, optional: true }], target: i0.ɵɵFactoryTarget.Injectable });
1138
- TableService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: TableService, providedIn: 'root' });
1139
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: TableService, decorators: [{
1140
- type: Injectable,
1141
- args: [{
1142
- providedIn: 'root',
1143
- }]
1144
- }], ctorParameters: function () { return [{ type: i1.AngularFirestore, decorators: [{
1145
- type: Optional
1146
- }] }, { type: i2.MatDialog, decorators: [{
1147
- type: Optional
1148
- }] }, { type: i3.ToastrService, decorators: [{
1149
- type: Optional
47
+ class TableService {
48
+ constructor(ngFire, dialog, toastr) {
49
+ this.ngFire = ngFire;
50
+ this.dialog = dialog;
51
+ this.toastr = toastr;
52
+ this.operators = {
53
+ '==': (a, b) => a === b,
54
+ '!=': (a, b) => a !== b,
55
+ '>': (a, b) => a > b,
56
+ '<': (a, b) => a < b,
57
+ '>=': (a, b) => a >= b,
58
+ '<=': (a, b) => a <= b,
59
+ in: (a, b) => Array.isArray(b) && b.includes(a),
60
+ 'not-in': (a, b) => Array.isArray(b) && !b.includes(a),
61
+ 'array-contains': (a, b) => Array.isArray(a) && a.includes(b),
62
+ 'array-contains-any': (a, b) => Array.isArray(a) &&
63
+ Array.isArray(b) &&
64
+ b.some((item) => a.includes(item)),
65
+ includes: (a, b) => a.includes(b), // Para strings ou arrays
66
+ };
67
+ }
68
+ async getItems(collection) {
69
+ try {
70
+ const querySnapshot = await collection.get();
71
+ return querySnapshot.docs.map((doc) => {
72
+ return { ...doc.data(), id: doc.id };
73
+ });
74
+ }
75
+ catch (error) {
76
+ console.warn('Collection não encontrada:', error);
77
+ return [];
78
+ }
79
+ }
80
+ async executeQuery(params) {
81
+ if (params.filterFn) {
82
+ // Lógica com filtro no cliente (filterFn)
83
+ const BATCH_FETCH_SIZE = params.batchSize;
84
+ const GOAL_SIZE = params.batchSize + 1;
85
+ if (params.navigation === 'forward' || params.navigation === 'reload') {
86
+ if (params.navigation === 'reload' && params.doc) {
87
+ params.doc.lastDoc = null;
88
+ }
89
+ let lastDocCursor = params.doc ? params.doc.lastDoc : null;
90
+ let pageResults = [];
91
+ let allFetchedDocs = [];
92
+ let hasMoreDocsInDb = true;
93
+ while (pageResults.length < GOAL_SIZE && hasMoreDocsInDb) {
94
+ let query = this.ngFire.collection(params.collection).ref;
95
+ query = this.applyFilters(query, params.arrange, params.conditions);
96
+ if (lastDocCursor) {
97
+ query = query.startAfter(lastDocCursor);
98
+ }
99
+ query = query.limit(BATCH_FETCH_SIZE);
100
+ const snapshot = await query.get();
101
+ if (snapshot.empty) {
102
+ hasMoreDocsInDb = false;
103
+ break;
104
+ }
105
+ lastDocCursor = snapshot.docs[snapshot.docs.length - 1];
106
+ allFetchedDocs.push(...snapshot.docs);
107
+ const batchUsers = snapshot.docs
108
+ .map((doc) => ({
109
+ id: doc.id,
110
+ ...doc.data(),
111
+ }))
112
+ .filter(params.filterFn);
113
+ pageResults.push(...batchUsers);
114
+ if (snapshot.size < BATCH_FETCH_SIZE) {
115
+ hasMoreDocsInDb = false;
116
+ }
117
+ }
118
+ const hasNextPage = pageResults.length > params.batchSize;
119
+ const finalItems = pageResults.slice(0, params.batchSize);
120
+ const firstDocOfPage = allFetchedDocs.find((doc) => doc.id === finalItems[0]?.id) || null;
121
+ const lastDocOfPage = allFetchedDocs.find((doc) => doc.id === finalItems[finalItems.length - 1]?.id) || null;
122
+ return {
123
+ items: finalItems,
124
+ filterLength: null,
125
+ firstDoc: firstDocOfPage,
126
+ lastDoc: lastDocOfPage,
127
+ hasNextPage: hasNextPage,
128
+ hasPreviousPage: !!(params.doc && params.doc.lastDoc) &&
129
+ params.navigation !== 'reload',
130
+ currentClientPageIndex: undefined,
131
+ };
132
+ }
133
+ // Lógica para trás (backward)
134
+ else if (params.navigation === 'backward') {
135
+ if (!params.doc || !params.doc.firstDoc) {
136
+ return {
137
+ items: [],
138
+ filterLength: null,
139
+ firstDoc: null,
140
+ lastDoc: null,
141
+ hasNextPage: true,
142
+ hasPreviousPage: false,
143
+ currentClientPageIndex: undefined,
144
+ };
145
+ }
146
+ let pageResults = [];
147
+ let allFetchedDocs = [];
148
+ let hasMoreDocsInDb = true;
149
+ let boundaryDoc = params.doc.firstDoc;
150
+ while (pageResults.length < GOAL_SIZE && hasMoreDocsInDb) {
151
+ let query = this.ngFire.collection(params.collection).ref;
152
+ query = this.applyFilters(query, params.arrange, params.conditions);
153
+ query = query.endBefore(boundaryDoc);
154
+ query = query.limitToLast(BATCH_FETCH_SIZE);
155
+ const snapshot = await query.get();
156
+ if (snapshot.empty) {
157
+ hasMoreDocsInDb = false;
158
+ break;
159
+ }
160
+ boundaryDoc = snapshot.docs[0];
161
+ allFetchedDocs = [...snapshot.docs, ...allFetchedDocs];
162
+ const batchUsers = snapshot.docs
163
+ .map((doc) => ({
164
+ id: doc.id,
165
+ ...doc.data(),
166
+ }))
167
+ .filter(params.filterFn);
168
+ pageResults = [...batchUsers, ...pageResults];
169
+ if (snapshot.size < BATCH_FETCH_SIZE) {
170
+ hasMoreDocsInDb = false;
171
+ }
172
+ }
173
+ const finalItems = pageResults.slice(0, params.batchSize);
174
+ const firstDocOfPage = allFetchedDocs.find((doc) => doc.id === finalItems[0]?.id) || null;
175
+ const lastDocOfPage = allFetchedDocs.find((doc) => doc.id === finalItems[finalItems.length - 1]?.id) || null;
176
+ return {
177
+ items: finalItems,
178
+ filterLength: null,
179
+ firstDoc: firstDocOfPage,
180
+ lastDoc: lastDocOfPage,
181
+ hasNextPage: true,
182
+ currentClientPageIndex: undefined,
183
+ };
184
+ }
185
+ }
186
+ else {
187
+ let items = [];
188
+ let docs = [];
189
+ let hasNextPage = false;
190
+ let filterLength = null;
191
+ let query = this.ngFire.collection(params.collection).ref;
192
+ if (params.conditions) {
193
+ params.conditions.forEach((c) => {
194
+ if (c.operator === '!=') {
195
+ query = query.orderBy(c.firestoreProperty);
196
+ }
197
+ });
198
+ }
199
+ query = this.applyFilters(query, params.arrange, params.conditions);
200
+ if (params.navigation === 'reload') {
201
+ query = query.limit(params.batchSize + 1);
202
+ if (params.doc && params.doc.firstDoc) {
203
+ query = query.startAt(params.doc.firstDoc);
204
+ }
205
+ }
206
+ else if (params.navigation === 'forward') {
207
+ query = query.limit(params.batchSize + 1);
208
+ if (params.doc && params.doc.lastDoc) {
209
+ query = query.startAfter(params.doc.lastDoc);
210
+ }
211
+ }
212
+ else {
213
+ // backward
214
+ query = query.limitToLast(params.batchSize + 1);
215
+ if (params.doc && params.doc.firstDoc) {
216
+ query = query.endBefore(params.doc.firstDoc);
217
+ }
218
+ }
219
+ const itemCol = await query.get();
220
+ itemCol.docs.forEach((doc) => docs.push(doc));
221
+ const itemPromises = docs.map(async (item) => {
222
+ const itemData = item.data();
223
+ items.push({ id: item.id, ...itemData });
224
+ });
225
+ let lastDoc = docs[docs.length - 1] || null;
226
+ let firstDoc = docs[0];
227
+ if ((items.length > params.batchSize && params.navigation === 'forward') ||
228
+ (params.navigation === 'reload' && items.length > params.batchSize)) {
229
+ lastDoc = docs[docs.length - 2] || null;
230
+ items.pop();
231
+ hasNextPage = true;
232
+ }
233
+ if (items.length > params.batchSize && params.navigation === 'backward') {
234
+ firstDoc = docs[1];
235
+ items.shift();
236
+ hasNextPage = true;
237
+ }
238
+ await Promise.all(itemPromises);
239
+ return {
240
+ items,
241
+ filterLength,
242
+ lastDoc,
243
+ firstDoc,
244
+ hasNextPage,
245
+ currentClientPageIndex: undefined,
246
+ };
247
+ }
248
+ // Fallback para garantir que sempre retornamos algo
249
+ return {
250
+ items: [],
251
+ filterLength: null,
252
+ firstDoc: null,
253
+ lastDoc: null,
254
+ hasNextPage: false,
255
+ currentClientPageIndex: undefined,
256
+ };
257
+ }
258
+ applyFilters(query, arrange, conditions) {
259
+ if (conditions) {
260
+ conditions.map((cond) => {
261
+ query = query.where(cond.firestoreProperty, cond.operator, cond.dashProperty);
262
+ });
263
+ }
264
+ let hasFilterSpecificOrderBy = false;
265
+ let appliedOrderByField = null;
266
+ const equalsFilters = arrange.filters.filter((f) => f.arrange === 'equals' && f.filter);
267
+ const otherFilters = arrange.filters.filter((f) => f.arrange !== 'equals');
268
+ const equalsGroupedByProperty = equalsFilters.reduce((acc, current) => {
269
+ const prop = current.filter.property;
270
+ if (!acc[prop]) {
271
+ acc[prop] = [];
272
+ }
273
+ acc[prop].push(current.filter.filtering);
274
+ return acc;
275
+ }, {});
276
+ for (const prop in equalsGroupedByProperty) {
277
+ const values = equalsGroupedByProperty[prop];
278
+ if (values.length > 0) {
279
+ query = query.where(prop, 'in', values);
280
+ }
281
+ }
282
+ otherFilters.forEach((filterItem) => {
283
+ // Aplicar filtragem por busca
284
+ if (filterItem.filter?.filtering &&
285
+ filterItem.filter?.property !== '' &&
286
+ filterItem.arrange === 'filter') {
287
+ query = query
288
+ .where(filterItem.filter.property, '>=', filterItem.filter.filtering.trim().toUpperCase())
289
+ .where(filterItem.filter.property, '<=', filterItem.filter.filtering.trim().toUpperCase() + '\uf8ff');
290
+ if (!hasFilterSpecificOrderBy) {
291
+ query = query.orderBy(filterItem.filter.property);
292
+ hasFilterSpecificOrderBy = true;
293
+ appliedOrderByField = filterItem.filter.property;
294
+ }
295
+ }
296
+ // Aplicar filtro do tipo "filterByDate"
297
+ if (filterItem.dateFilter && filterItem.arrange === 'filterByDate') {
298
+ query = query
299
+ .where(arrange.sortBy.field, '>=', filterItem.dateFilter.initial)
300
+ .where(arrange.sortBy.field, '<=', filterItem.dateFilter.final);
301
+ if (!hasFilterSpecificOrderBy) {
302
+ query = query.orderBy(arrange.sortBy.field);
303
+ hasFilterSpecificOrderBy = true;
304
+ appliedOrderByField = arrange.sortBy.field;
305
+ }
306
+ }
307
+ });
308
+ // Aplicar sortBy
309
+ if (arrange.sortBy && arrange.sortBy.field && arrange.sortBy.order) {
310
+ if (appliedOrderByField !== arrange.sortBy.field) {
311
+ query = query.orderBy(arrange.sortBy.field, arrange.sortBy.order);
312
+ }
313
+ }
314
+ return query;
315
+ }
316
+ getIdFilter(params) {
317
+ if (!params.arrange?.filters)
318
+ return null;
319
+ const idFilter = params.arrange.filters.find((f) => f.arrange === 'filter' &&
320
+ f.filter?.property === 'id' &&
321
+ f.filter?.filtering);
322
+ return idFilter?.filter?.filtering?.trim() || null;
323
+ }
324
+ async getDocumentById(collection, docId) {
325
+ try {
326
+ const docRef = this.ngFire.collection(collection).doc(docId);
327
+ const docSnapshot = await docRef.get().toPromise();
328
+ if (docSnapshot && docSnapshot.exists) {
329
+ return {
330
+ id: docSnapshot.id,
331
+ ...docSnapshot.data(),
332
+ };
333
+ }
334
+ return null;
335
+ }
336
+ catch (error) {
337
+ console.warn('Erro ao buscar documento por ID:', error);
338
+ return null;
339
+ }
340
+ }
341
+ async searchByIdPartial(params, searchTerm) {
342
+ const exactMatch = await this.getDocumentById(params.collection, searchTerm);
343
+ if (exactMatch) {
344
+ if (params.conditions) {
345
+ const operators = this.operators;
346
+ const passesConditions = params.conditions.every((cond) => {
347
+ const operatorFn = operators[cond.operator];
348
+ return operatorFn
349
+ ? operatorFn(exactMatch[cond.firestoreProperty], cond.dashProperty)
350
+ : false;
351
+ });
352
+ if (!passesConditions) {
353
+ return {
354
+ items: [],
355
+ filterLength: 0,
356
+ firstDoc: null,
357
+ lastDoc: null,
358
+ hasNextPage: false,
359
+ hasPreviousPage: false,
360
+ currentClientPageIndex: 0,
361
+ totalPages: 0,
362
+ };
363
+ }
364
+ }
365
+ if (params.filterFn && !params.filterFn(exactMatch)) {
366
+ return {
367
+ items: [],
368
+ filterLength: 0,
369
+ firstDoc: null,
370
+ lastDoc: null,
371
+ hasNextPage: false,
372
+ hasPreviousPage: false,
373
+ currentClientPageIndex: 0,
374
+ totalPages: 0,
375
+ };
376
+ }
377
+ return {
378
+ items: [exactMatch],
379
+ filterLength: 1,
380
+ firstDoc: null,
381
+ lastDoc: null,
382
+ hasNextPage: false,
383
+ hasPreviousPage: false,
384
+ currentClientPageIndex: 0,
385
+ totalPages: 1,
386
+ };
387
+ }
388
+ const searchTermLower = searchTerm.toLowerCase();
389
+ const paramsWithoutIdFilter = {
390
+ ...params,
391
+ arrange: {
392
+ ...params.arrange,
393
+ filters: params.arrange.filters.filter((f) => !(f.arrange === 'filter' && f.filter?.property === 'id')),
394
+ },
395
+ };
396
+ let query = this.ngFire.collection(params.collection).ref;
397
+ // Aplicar conditions
398
+ if (params.conditions) {
399
+ params.conditions.forEach((cond) => {
400
+ query = query.where(cond.firestoreProperty, cond.operator, cond.dashProperty);
401
+ });
402
+ }
403
+ // Aplicar sortBy
404
+ if (params.arrange?.sortBy?.field && params.arrange?.sortBy?.order) {
405
+ query = query.orderBy(params.arrange.sortBy.field, params.arrange.sortBy.order);
406
+ }
407
+ const snapshot = await query.get();
408
+ let items = snapshot.docs
409
+ .map((doc) => ({
410
+ id: doc.id,
411
+ ...doc.data(),
412
+ }))
413
+ .filter((item) => item.id.toLowerCase().includes(searchTermLower));
414
+ // Separar equals filters e outros filtros
415
+ const equalsFilters = paramsWithoutIdFilter.arrange.filters.filter((f) => f.arrange === 'equals' && f.filter);
416
+ const otherFilters = paramsWithoutIdFilter.arrange.filters.filter((f) => f.arrange !== 'equals' &&
417
+ (f.arrange !== 'filter' || f.filter?.property !== 'id'));
418
+ // Aplicar equals filters com lógica OR dentro de cada propriedade
419
+ if (equalsFilters.length > 0) {
420
+ // Agrupar por propriedade para aplicar OR
421
+ const groupedByProperty = equalsFilters.reduce((acc, f) => {
422
+ const prop = f.filter.property;
423
+ if (!acc[prop]) {
424
+ acc[prop] = [];
425
+ }
426
+ acc[prop].push(f.filter.filtering);
427
+ return acc;
428
+ }, {});
429
+ // Filtrar: item deve ter pelo menos um valor de CADA propriedade
430
+ items = items.filter((item) => {
431
+ return Object.entries(groupedByProperty).every(([prop, values]) => {
432
+ return values.includes(item[prop]);
433
+ });
434
+ });
435
+ }
436
+ // Aplicar outros filtros
437
+ otherFilters.forEach((filterItem) => {
438
+ if (filterItem.arrange === 'filter' &&
439
+ filterItem.filter?.filtering &&
440
+ filterItem.filter?.property) {
441
+ const filterValue = String(filterItem.filter.filtering)
442
+ .trim()
443
+ .toLowerCase();
444
+ items = items.filter((item) => {
445
+ const itemValue = String(item[filterItem.filter.property]).toLowerCase();
446
+ return itemValue.includes(filterValue);
447
+ });
448
+ }
449
+ });
450
+ // Aplicar filterFn se existir
451
+ if (params.filterFn) {
452
+ items = items.filter(params.filterFn);
453
+ }
454
+ // Paginação
455
+ const pageSize = params.batchSize;
456
+ let currentClientPageIndex = 0;
457
+ if (params.navigation === 'reload') {
458
+ currentClientPageIndex = 0;
459
+ }
460
+ else {
461
+ // Usar o índice passado pelo componente sem incrementar/decrementar
462
+ currentClientPageIndex = params.clientPageIndex || 0;
463
+ }
464
+ const startIndex = currentClientPageIndex * pageSize;
465
+ const endIndex = startIndex + pageSize;
466
+ const paginatedItems = items.slice(startIndex, endIndex);
467
+ const totalPages = Math.ceil(items.length / pageSize);
468
+ const hasNextPage = currentClientPageIndex < totalPages - 1;
469
+ const hasPreviousPage = currentClientPageIndex > 0;
470
+ return {
471
+ items: paginatedItems,
472
+ filterLength: items.length,
473
+ firstDoc: null,
474
+ lastDoc: null,
475
+ hasNextPage,
476
+ hasPreviousPage,
477
+ currentClientPageIndex,
478
+ totalPages,
479
+ };
480
+ }
481
+ shouldUseClientSideFallback(params) {
482
+ const hasConditions = params.conditions && params.conditions.length > 0;
483
+ const hasArrangeFilters = params.arrange?.filters && params.arrange.filters.length > 0;
484
+ const hasSortBy = params.arrange?.sortBy?.field;
485
+ if (params.filterFn) {
486
+ return false;
487
+ }
488
+ if (hasArrangeFilters) {
489
+ const equalsFilters = params.arrange.filters.filter((f) => f.arrange === 'equals' && f.filter);
490
+ if (equalsFilters.length > 0) {
491
+ const propertiesSet = new Set(equalsFilters.map((f) => f.filter.property));
492
+ if (propertiesSet.size > 1) {
493
+ return true;
494
+ }
495
+ }
496
+ }
497
+ if (hasConditions && hasArrangeFilters && hasSortBy) {
498
+ return true;
499
+ }
500
+ if (hasConditions && hasArrangeFilters) {
501
+ return true;
502
+ }
503
+ if (hasArrangeFilters && params.arrange.filters.length > 1 && hasSortBy) {
504
+ const equalsFilters = params.arrange.filters.filter((f) => f.arrange === 'equals' && f.filter);
505
+ if (equalsFilters.length > 0) {
506
+ const propertiesSet = new Set(equalsFilters.map((f) => f.filter.property));
507
+ if (propertiesSet.size === 1 &&
508
+ equalsFilters.length === params.arrange.filters.length) {
509
+ return false;
510
+ }
511
+ }
512
+ return true;
513
+ }
514
+ return false;
515
+ }
516
+ async getPaginated(params) {
517
+ const idFilterValue = this.getIdFilter(params);
518
+ if (idFilterValue) {
519
+ const result = await this.searchByIdPartial(params, idFilterValue);
520
+ return result;
521
+ }
522
+ // Detectar preventivamente se deve usar fallback
523
+ if (this.shouldUseClientSideFallback(params)) {
524
+ await this.trackMissingIndexPreventive(params.collection, params.arrange, params.conditions);
525
+ const result = await this.executeClientSideQuery(params);
526
+ console.log('📊 [TABLE] Resultados paginados via fallback client-side:', {
527
+ totalItems: result.filterLength,
528
+ returnedItems: result.items.length,
529
+ hasNextPage: result.hasNextPage,
530
+ currentPage: (result.currentClientPageIndex || 0) + 1,
531
+ });
532
+ return result;
533
+ }
534
+ try {
535
+ const result = await this.executeQuery(params);
536
+ console.log('📊 [TABLE] Resultados paginados via Firestore:', {
537
+ totalItems: result.filterLength || 'N/A',
538
+ returnedItems: result.items.length,
539
+ hasNextPage: result.hasNextPage,
540
+ });
541
+ return result;
542
+ }
543
+ catch (error) {
544
+ if (error && error.code === 'failed-precondition') {
545
+ await this.trackMissingIndex(error, params.collection, params.arrange, params.conditions);
546
+ const result = await this.executeClientSideQuery(params);
547
+ console.log('📊 [TABLE] Resultados paginados via fallback (erro de index):', {
548
+ totalItems: result.filterLength,
549
+ returnedItems: result.items.length,
550
+ hasNextPage: result.hasNextPage,
551
+ currentPage: (result.currentClientPageIndex || 0) + 1,
552
+ });
553
+ return result;
554
+ }
555
+ else if (error && error.code === 'invalid-argument') {
556
+ await this.trackMissingIndex(error, params.collection, params.arrange, params.conditions);
557
+ const result = await this.executeClientSideQuery(params);
558
+ console.log('📊 [TABLE] Resultados paginados via fallback (argumento inválido):', {
559
+ totalItems: result.filterLength,
560
+ returnedItems: result.items.length,
561
+ hasNextPage: result.hasNextPage,
562
+ currentPage: (result.currentClientPageIndex || 0) + 1,
563
+ });
564
+ return result;
565
+ }
566
+ else {
567
+ throw error;
568
+ }
569
+ }
570
+ }
571
+ async executeClientSideQuery(params) {
572
+ // Otimizar usando pelo menos uma cláusula .where() quando possível
573
+ let query = this.ngFire.collection(params.collection).ref;
574
+ let appliedCondition = null;
575
+ let hasAppliedWhereClause = false;
576
+ // Primeiro, tenta aplicar condições simples
577
+ if (params.conditions && params.conditions.length > 0) {
578
+ const simpleCondition = params.conditions.find((cond) => ['==', '>', '<', '>=', '<=', 'in', 'array-contains'].includes(cond.operator));
579
+ if (simpleCondition) {
580
+ query = query.where(simpleCondition.firestoreProperty, simpleCondition.operator, simpleCondition.dashProperty);
581
+ appliedCondition = simpleCondition;
582
+ hasAppliedWhereClause = true;
583
+ }
584
+ }
585
+ // Se não há condições disponíveis, tenta aplicar filtros do arrange
586
+ let appliedFirestoreFilter = null;
587
+ if (!hasAppliedWhereClause && params.arrange?.filters) {
588
+ // Agrupar equals filters por propriedade
589
+ const equalsFilters = params.arrange.filters.filter((f) => f.arrange === 'equals' && f.filter);
590
+ const equalsGroupedByProperty = equalsFilters.reduce((acc, current) => {
591
+ const prop = current.filter.property;
592
+ if (!acc[prop]) {
593
+ acc[prop] = [];
594
+ }
595
+ acc[prop].push(current.filter.filtering);
596
+ return acc;
597
+ }, {});
598
+ // Se há apenas UMA propriedade com múltiplos valores, aplicar no Firestore com 'in'
599
+ const properties = Object.keys(equalsGroupedByProperty);
600
+ if (properties.length === 1 && equalsFilters.length > 0) {
601
+ const prop = properties[0];
602
+ const values = equalsGroupedByProperty[prop];
603
+ query = query.where(prop, 'in', values);
604
+ hasAppliedWhereClause = true;
605
+ // Marcar TODOS os equals filters dessa propriedade como aplicados
606
+ appliedFirestoreFilter = 'all-equals';
607
+ }
608
+ else if (properties.length === 0) {
609
+ const otherFilter = params.arrange.filters.find((f) => (f.arrange === 'filter' &&
610
+ f.filter?.filtering &&
611
+ f.filter?.property) ||
612
+ (f.arrange === 'filterByDate' &&
613
+ f.dateFilter?.initial &&
614
+ f.dateFilter?.final));
615
+ if (otherFilter) {
616
+ if (otherFilter.arrange === 'filter' && otherFilter.filter) {
617
+ const filterValue = otherFilter.filter.filtering
618
+ .trim()
619
+ .toUpperCase();
620
+ query = query
621
+ .where(otherFilter.filter.property, '>=', filterValue)
622
+ .where(otherFilter.filter.property, '<=', filterValue + '\uf8ff');
623
+ hasAppliedWhereClause = true;
624
+ appliedFirestoreFilter = otherFilter;
625
+ }
626
+ else if (otherFilter.arrange === 'filterByDate' &&
627
+ otherFilter.dateFilter &&
628
+ params.arrange.sortBy?.field) {
629
+ query = query
630
+ .where(params.arrange.sortBy.field, '>=', otherFilter.dateFilter.initial)
631
+ .where(params.arrange.sortBy.field, '<=', otherFilter.dateFilter.final);
632
+ hasAppliedWhereClause = true;
633
+ appliedFirestoreFilter = otherFilter;
634
+ }
635
+ }
636
+ }
637
+ }
638
+ const allDocsSnapshot = await query.get();
639
+ let items = allDocsSnapshot.docs.map((doc) => ({
640
+ id: doc.id,
641
+ ...doc.data(),
642
+ }));
643
+ // Aplicar condições restantes
644
+ if (params.conditions) {
645
+ const remainingConditions = params.conditions.filter((cond) => cond !== appliedCondition);
646
+ if (remainingConditions.length > 0) {
647
+ const operators = this.operators;
648
+ items = items.filter((item) => {
649
+ return remainingConditions.every((cond) => {
650
+ const operatorFn = operators[cond.operator];
651
+ return operatorFn
652
+ ? operatorFn(item[cond.firestoreProperty], cond.dashProperty)
653
+ : false;
654
+ });
655
+ });
656
+ }
657
+ }
658
+ const { filters, sortBy } = params.arrange;
659
+ // Track which filter was already applied in Firestore to avoid double filtering
660
+ if (hasAppliedWhereClause && !appliedCondition && params.arrange?.filters) {
661
+ const equalsFilter = params.arrange.filters.find((f) => f.arrange === 'equals' && f.filter?.filtering);
662
+ if (equalsFilter) {
663
+ appliedFirestoreFilter = equalsFilter;
664
+ }
665
+ else {
666
+ appliedFirestoreFilter = params.arrange.filters.find((f) => (f.arrange === 'filter' &&
667
+ f.filter?.filtering &&
668
+ f.filter?.property) ||
669
+ (f.arrange === 'filterByDate' &&
670
+ f.dateFilter?.initial &&
671
+ f.dateFilter?.final));
672
+ }
673
+ }
674
+ const equalsFilters = filters.filter((f) => f.arrange === 'equals');
675
+ const otherFilters = filters.filter((f) => f.arrange !== 'equals');
676
+ // Aplicar equals filters no client-side apenas se não foram aplicados no Firestore
677
+ if (appliedFirestoreFilter !== 'all-equals' && equalsFilters.length > 0) {
678
+ // Agrupar por propriedade para aplicar OR dentro de cada propriedade
679
+ const groupedByProperty = equalsFilters.reduce((acc, f) => {
680
+ const prop = f.filter.property;
681
+ if (!acc[prop]) {
682
+ acc[prop] = [];
683
+ }
684
+ acc[prop].push(f.filter.filtering);
685
+ return acc;
686
+ }, {});
687
+ // Filtrar: item deve ter pelo menos um valor de CADA propriedade
688
+ // (AND entre propriedades, OR dentro de cada propriedade)
689
+ items = items.filter((item) => {
690
+ return Object.entries(groupedByProperty).every(([prop, values]) => {
691
+ return values.includes(item[prop]);
692
+ });
693
+ });
694
+ }
695
+ otherFilters.forEach((filterItem) => {
696
+ if (appliedFirestoreFilter === filterItem) {
697
+ return;
698
+ }
699
+ if (filterItem.arrange === 'filter' &&
700
+ filterItem.filter?.filtering &&
701
+ filterItem.filter?.property) {
702
+ const filterValue = String(filterItem.filter.filtering)
703
+ .trim()
704
+ .toLowerCase();
705
+ items = items.filter((item) => {
706
+ const itemValue = String(item[filterItem.filter.property]).toLowerCase();
707
+ return itemValue.includes(filterValue);
708
+ });
709
+ }
710
+ if (filterItem.arrange === 'filterByDate' &&
711
+ filterItem.dateFilter?.initial &&
712
+ filterItem.dateFilter?.final &&
713
+ sortBy.field) {
714
+ items = items.filter((item) => {
715
+ try {
716
+ const fieldValue = item[sortBy.field];
717
+ if (!fieldValue) {
718
+ return false;
719
+ }
720
+ let itemDate;
721
+ if (typeof fieldValue.toDate === 'function') {
722
+ itemDate = fieldValue.toDate();
723
+ }
724
+ else if (fieldValue instanceof Date) {
725
+ itemDate = fieldValue;
726
+ }
727
+ else if (typeof fieldValue === 'string') {
728
+ itemDate = new Date(fieldValue);
729
+ if (isNaN(itemDate.getTime())) {
730
+ return false;
731
+ }
732
+ }
733
+ else if (typeof fieldValue === 'number') {
734
+ itemDate = new Date(fieldValue);
735
+ }
736
+ else {
737
+ return false;
738
+ }
739
+ return (itemDate >= filterItem.dateFilter.initial &&
740
+ itemDate <= filterItem.dateFilter.final);
741
+ }
742
+ catch (error) {
743
+ console.warn('Erro ao processar filtro de data para o item:', item.id, error);
744
+ return false;
745
+ }
746
+ });
747
+ }
748
+ });
749
+ // Aplicar filterFn se existir
750
+ if (params.filterFn) {
751
+ items = items.filter(params.filterFn);
752
+ }
753
+ if (sortBy && sortBy.field && sortBy.order) {
754
+ items.sort((a, b) => {
755
+ const valA = a[sortBy.field];
756
+ const valB = b[sortBy.field];
757
+ if (valA < valB) {
758
+ return sortBy.order === 'asc' ? -1 : 1;
759
+ }
760
+ if (valA > valB) {
761
+ return sortBy.order === 'asc' ? 1 : -1;
762
+ }
763
+ return 0;
764
+ });
765
+ }
766
+ // Implementação adequada da paginação
767
+ let currentClientPageIndex = 0;
768
+ // Determinar a página atual baseada na navegação
769
+ if (params.navigation === 'reload') {
770
+ currentClientPageIndex = 0;
771
+ }
772
+ else {
773
+ currentClientPageIndex = params.clientPageIndex || 0;
774
+ }
775
+ const pageSize = params.batchSize;
776
+ const startIndex = currentClientPageIndex * pageSize;
777
+ const endIndex = startIndex + pageSize;
778
+ const paginatedItems = items.slice(startIndex, endIndex);
779
+ const totalPages = Math.ceil(items.length / pageSize);
780
+ const hasNextPage = currentClientPageIndex < totalPages - 1;
781
+ const hasPreviousPage = currentClientPageIndex > 0;
782
+ return {
783
+ items: paginatedItems,
784
+ filterLength: items.length,
785
+ lastDoc: null,
786
+ firstDoc: null,
787
+ hasNextPage: hasNextPage,
788
+ hasPreviousPage: hasPreviousPage,
789
+ currentClientPageIndex: currentClientPageIndex,
790
+ totalPages: totalPages,
791
+ };
792
+ }
793
+ async getItemsData(collection, arrange, conditions = undefined) {
794
+ try {
795
+ let query = this.ngFire.collection(collection).ref;
796
+ query = this.applyFilters(query, arrange, conditions);
797
+ const snapshot = await query.get();
798
+ return await Promise.all(snapshot.docs.map(async (doc) => {
799
+ const data = doc.data();
800
+ const id = doc.id;
801
+ return {
802
+ id,
803
+ ...data,
804
+ };
805
+ }));
806
+ }
807
+ catch (e) {
808
+ throw e;
809
+ }
810
+ }
811
+ async deleteIndex(id, col) {
812
+ try {
813
+ const batch = this.ngFire.firestore.batch();
814
+ const docRef = this.ngFire.collection(col).doc(id);
815
+ const docSnapshot = (await firstValueFrom(docRef.get()));
816
+ const doc = docSnapshot.data();
817
+ batch.delete(docRef.ref);
818
+ if (doc && typeof doc.index === 'number') {
819
+ await this.reindex(doc.index, col, batch);
820
+ }
821
+ await batch.commit();
822
+ this.toastr.success('Item excluído com sucesso!');
823
+ return true;
824
+ }
825
+ catch (e) {
826
+ const error = e;
827
+ console.error('Erro ao deletar item:', error);
828
+ this.toastr.error('Erro ao deletar item.');
829
+ return false;
830
+ }
831
+ }
832
+ async reindex(index, col, batch) {
833
+ try {
834
+ const snapshot = (await firstValueFrom(this.ngFire.collection(col).get()));
835
+ const docs = snapshot.docs;
836
+ for (let doc of docs) {
837
+ const data = doc.data();
838
+ if (data && typeof data.index === 'number' && data.index > index) {
839
+ data.index--;
840
+ const docRef = this.ngFire.collection(col).doc(doc.id).ref;
841
+ batch.update(docRef, data);
842
+ }
843
+ }
844
+ }
845
+ catch (error) {
846
+ console.error('Erro ao reindexar:', error);
847
+ }
848
+ return;
849
+ }
850
+ dateFormatValidator() {
851
+ return (control) => {
852
+ if (!control.value) {
853
+ return null;
854
+ }
855
+ const dateStr = control.value.trim();
856
+ const datePattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
857
+ if (!datePattern.test(dateStr)) {
858
+ return { invalidFormat: true };
859
+ }
860
+ const parts = dateStr.split('/');
861
+ const day = parts[0].padStart(2, '0');
862
+ const month = parts[1].padStart(2, '0');
863
+ const year = parts[2];
864
+ const normalizedDate = `${day}/${month}/${year}`;
865
+ const date = moment(normalizedDate, 'DD/MM/YYYY', true);
866
+ if (!date.isValid()) {
867
+ return { invalidDate: true };
868
+ }
869
+ return null;
870
+ };
871
+ }
872
+ async updateIndex(index, id, col) {
873
+ await this.ngFire.collection(col).doc(id).update({ index });
874
+ }
875
+ /**
876
+ * Extrai o link de criação de índice da mensagem de erro do Firestore
877
+ */
878
+ extractIndexLink(error) {
879
+ if (!error || !error.message)
880
+ return null;
881
+ const linkMatch = error.message.match(/(https:\/\/console\.firebase\.google\.com\/[^\s]+)/);
882
+ return linkMatch ? linkMatch[1] : null;
883
+ }
884
+ /**
885
+ * Rastreia índices ausentes ao usar fallback preventivo
886
+ */
887
+ async trackMissingIndexPreventive(collection, arrange, conditions = undefined) {
888
+ try {
889
+ const querySignature = this.generateQuerySignature(collection, arrange, conditions);
890
+ const docId = `${collection}_${querySignature}`;
891
+ const indexLink = this.generateIndexLink(collection, arrange, conditions);
892
+ const indexInstructions = this.generateIndexInstructions(collection, arrange, conditions);
893
+ const trackingData = {
894
+ collection,
895
+ indexLink,
896
+ indexInstructions,
897
+ arrange: {
898
+ sortBy: arrange.sortBy,
899
+ filters: arrange.filters?.map((f) => ({
900
+ arrange: f.arrange,
901
+ property: f.filter?.property || null,
902
+ dateField: f.arrange === 'filterByDate' ? arrange.sortBy?.field : null,
903
+ })) || [],
904
+ },
905
+ conditions: conditions?.map((c) => ({
906
+ property: c.firestoreProperty,
907
+ operator: c.operator,
908
+ })) || [],
909
+ errorMessage: `Fallback preventivo usado para a collection ${collection}. A query exigiria índice composto.`,
910
+ updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
911
+ };
912
+ console.log('📄 [INDEX LINK] Dados que serão salvos no documento:', {
913
+ docId,
914
+ collection: trackingData.collection,
915
+ indexLink: trackingData.indexLink,
916
+ arrange: trackingData.arrange,
917
+ conditions: trackingData.conditions,
918
+ errorMessage: trackingData.errorMessage,
919
+ });
920
+ const docRef = this.ngFire.collection('missingIndexes').doc(docId);
921
+ const doc = await docRef.get().toPromise();
922
+ if (doc && doc.exists) {
923
+ await docRef.update({
924
+ count: firebase.firestore.FieldValue.increment(1),
925
+ updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
926
+ lastError: trackingData.errorMessage,
927
+ });
928
+ }
929
+ else {
930
+ await docRef.set({
931
+ ...trackingData,
932
+ count: 1,
933
+ createdAt: firebase.firestore.FieldValue.serverTimestamp(),
934
+ });
935
+ }
936
+ }
937
+ catch (trackingError) {
938
+ console.warn('Falha ao rastrear fallback preventivo:', trackingError);
939
+ }
940
+ }
941
+ /**
942
+ * Gera uma assinatura única para uma query
943
+ */
944
+ generateQuerySignature(collection, arrange, conditions = undefined) {
945
+ const signature = {
946
+ collection,
947
+ sortBy: arrange.sortBy,
948
+ filters: arrange.filters?.map((f) => ({
949
+ arrange: f.arrange,
950
+ property: f.filter?.property || null,
951
+ })) || [],
952
+ conditions: conditions?.map((c) => ({
953
+ property: c.firestoreProperty,
954
+ operator: c.operator,
955
+ })) || [],
956
+ };
957
+ return btoa(JSON.stringify(signature))
958
+ .replace(/[^a-zA-Z0-9]/g, '')
959
+ .substring(0, 20);
960
+ }
961
+ /**
962
+ * Gera instruções claras para criar o índice manualmente
963
+ */
964
+ generateIndexInstructions(collection, arrange, conditions = undefined) {
965
+ const instructions = {
966
+ summary: '',
967
+ collection: collection,
968
+ fields: [],
969
+ queryExample: '',
970
+ stepByStep: [],
971
+ notes: [],
972
+ };
973
+ const fields = [];
974
+ if (conditions && conditions.length > 0) {
975
+ conditions.forEach((condition) => {
976
+ if (condition.firestoreProperty) {
977
+ fields.push({
978
+ field: condition.firestoreProperty,
979
+ order: 'Ascending',
980
+ type: 'WHERE clause',
981
+ operator: condition.operator,
982
+ description: `Filtrar por ${condition.firestoreProperty} usando operador ${condition.operator}`,
983
+ });
984
+ }
985
+ });
986
+ }
987
+ if (arrange.filters && arrange.filters.length > 0) {
988
+ arrange.filters.forEach((filter) => {
989
+ if (filter.filter?.property) {
990
+ fields.push({
991
+ field: filter.filter.property,
992
+ order: 'Ascending',
993
+ type: 'WHERE clause (filter)',
994
+ operator: filter.arrange === 'filter' ? 'CONTAINS' : 'RANGE',
995
+ description: `Filtrar por ${filter.filter.property} usando filtro ${filter.arrange}`,
996
+ });
997
+ }
998
+ });
999
+ }
1000
+ if (arrange.sortBy?.field) {
1001
+ fields.push({
1002
+ field: arrange.sortBy.field,
1003
+ order: arrange.sortBy.order === 'desc' ? 'Descending' : 'Ascending',
1004
+ type: 'ORDER BY clause',
1005
+ operator: 'N/A',
1006
+ description: `Ordenar resultados por ${arrange.sortBy.field} em ordem ${arrange.sortBy.order}`,
1007
+ });
1008
+ }
1009
+ instructions.fields = fields;
1010
+ const fieldNames = fields.map((f) => f.field).join(' + ');
1011
+ instructions.summary = `Criar índice composto para ${collection}: ${fieldNames}`;
1012
+ let queryExample = `db.collection('${collection}')`;
1013
+ fields.forEach((field, index) => {
1014
+ if (field.type.includes('WHERE')) {
1015
+ if (field.operator === '==') {
1016
+ queryExample += `\n .where('${field.field}', '==', 'value')`;
1017
+ }
1018
+ else if (field.operator === 'CONTAINS') {
1019
+ queryExample += `\n .where('${field.field}', '>=', 'searchText')`;
1020
+ }
1021
+ else {
1022
+ queryExample += `\n .where('${field.field}', '${field.operator}', 'value')`;
1023
+ }
1024
+ }
1025
+ });
1026
+ const orderByField = fields.find((f) => f.type.includes('ORDER BY'));
1027
+ if (orderByField) {
1028
+ queryExample += `\n .orderBy('${orderByField.field}', '${orderByField.order.toLowerCase()}')`;
1029
+ }
1030
+ instructions.queryExample = queryExample;
1031
+ instructions.stepByStep = [
1032
+ '1. Ir para Firebase Console → Firestore → Indexes',
1033
+ '2. Clicar em "Create Index"',
1034
+ `3. Definir Collection ID: ${collection}`,
1035
+ '4. Configurar campos nesta ORDEM EXATA:',
1036
+ ...fields.map((field, index) => ` ${index + 1}. Campo: ${field.field}, Order: ${field.order}, Array: No`),
1037
+ '5. Definir Query scopes: Collection',
1038
+ '6. Clicar em "Create" e aguardar conclusão',
1039
+ ];
1040
+ instructions.notes = [
1041
+ '⚠️ A ordem dos campos é CRÍTICA - deve corresponder exatamente à ordem da query',
1042
+ '⚠️ As cláusulas WHERE devem vir ANTES do campo ORDER BY',
1043
+ '⚠️ Este índice só funcionará para queries com esta combinação EXATA de campos',
1044
+ '⚠️ A criação do índice pode levar vários minutos',
1045
+ ];
1046
+ return instructions;
1047
+ }
1048
+ /**
1049
+ * Gera um link de índice baseado na estrutura da query
1050
+ */
1051
+ generateIndexLink(collection, arrange, conditions = undefined) {
1052
+ try {
1053
+ const indexFields = [];
1054
+ if (conditions && conditions.length > 0) {
1055
+ conditions.forEach((condition) => {
1056
+ if (condition.firestoreProperty) {
1057
+ indexFields.push(condition.firestoreProperty);
1058
+ }
1059
+ });
1060
+ }
1061
+ if (arrange.filters && arrange.filters.length > 0) {
1062
+ arrange.filters.forEach((filter) => {
1063
+ if (filter.filter?.property) {
1064
+ indexFields.push(filter.filter.property);
1065
+ }
1066
+ });
1067
+ }
1068
+ if (arrange.sortBy?.field) {
1069
+ indexFields.push(arrange.sortBy.field);
1070
+ }
1071
+ if (indexFields.length > 1) {
1072
+ const baseUrl = 'https://console.firebase.google.com/project/toppayy-dev/firestore/indexes';
1073
+ const queryParams = new URLSearchParams({
1074
+ create_composite: `collection=${collection}&fields=${indexFields.join(',')}`,
1075
+ });
1076
+ const finalLink = `${baseUrl}?${queryParams.toString()}`;
1077
+ return finalLink;
1078
+ }
1079
+ return null;
1080
+ }
1081
+ catch (error) {
1082
+ console.warn('Falha ao gerar link de índice:', error);
1083
+ return null;
1084
+ }
1085
+ }
1086
+ async trackMissingIndex(error, collection, arrange, conditions = undefined) {
1087
+ try {
1088
+ const indexLink = this.extractIndexLink(error);
1089
+ if (!indexLink)
1090
+ return;
1091
+ const linkHash = btoa(indexLink)
1092
+ .replace(/[^a-zA-Z0-9]/g, '')
1093
+ .substring(0, 20);
1094
+ const docId = `${collection}_${linkHash}`;
1095
+ const indexInstructions = this.generateIndexInstructions(collection, arrange, conditions);
1096
+ const trackingData = {
1097
+ collection,
1098
+ indexLink,
1099
+ indexInstructions,
1100
+ arrange: {
1101
+ sortBy: arrange.sortBy,
1102
+ filters: arrange.filters?.map((f) => ({
1103
+ arrange: f.arrange,
1104
+ property: f.filter?.property || null,
1105
+ dateField: f.arrange === 'filterByDate' ? arrange.sortBy?.field : null,
1106
+ })) || [],
1107
+ },
1108
+ conditions: conditions?.map((c) => ({
1109
+ property: c.firestoreProperty,
1110
+ operator: c.operator,
1111
+ })) || [],
1112
+ errorMessage: error.message,
1113
+ updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
1114
+ };
1115
+ const docRef = this.ngFire.collection('missingIndexes').doc(docId);
1116
+ const doc = await docRef.get().toPromise();
1117
+ if (doc && doc.exists) {
1118
+ await docRef.update({
1119
+ count: firebase.firestore.FieldValue.increment(1),
1120
+ updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
1121
+ lastError: error.message,
1122
+ });
1123
+ }
1124
+ else {
1125
+ await docRef.set({
1126
+ ...trackingData,
1127
+ count: 1,
1128
+ createdAt: firebase.firestore.FieldValue.serverTimestamp(),
1129
+ });
1130
+ }
1131
+ }
1132
+ catch (trackingError) {
1133
+ console.warn('Falha ao rastrear índice ausente:', trackingError);
1134
+ }
1135
+ }
1136
+ }
1137
+ TableService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: TableService, deps: [{ token: i1.AngularFirestore, optional: true }, { token: i2.MatDialog, optional: true }, { token: i3.ToastrService, optional: true }], target: i0.ɵɵFactoryTarget.Injectable });
1138
+ TableService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: TableService, providedIn: 'root' });
1139
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: TableService, decorators: [{
1140
+ type: Injectable,
1141
+ args: [{
1142
+ providedIn: 'root',
1143
+ }]
1144
+ }], ctorParameters: function () { return [{ type: i1.AngularFirestore, decorators: [{
1145
+ type: Optional
1146
+ }] }, { type: i2.MatDialog, decorators: [{
1147
+ type: Optional
1148
+ }] }, { type: i3.ToastrService, decorators: [{
1149
+ type: Optional
1150
1150
  }] }]; } });
1151
1151
 
1152
- class TableComponent {
1153
- // CONSTRUCTOR
1154
- constructor(router, tableService, firestore) {
1155
- this.router = router;
1156
- this.tableService = tableService;
1157
- this.firestore = firestore;
1158
- this.arrange = null;
1159
- this.currentPageNumber = 1;
1160
- this.currentClientPageIndex = 0;
1161
- this.items = [];
1162
- this.isLoading = false;
1163
- this.lastDoc = null;
1164
- this.firstDoc = null;
1165
- this.sortBy = {
1166
- field: 'createdAt',
1167
- order: 'desc',
1168
- };
1169
- this.columnProperties = [];
1170
- this.selectSort = new FormControl('');
1171
- this.currentArrange = '';
1172
- this.hasNextPage = false;
1173
- this.dropdownItems = [];
1174
- this.sortableDropdownItems = [];
1175
- this.pageSize = 25;
1176
- this.totalItems = 0;
1177
- this.filterValue = null;
1178
- this.hasFilterableColumn = false;
1179
- this.hasSortableColumn = false;
1180
- this.filterSubject = new Subject();
1181
- this.debounceTimeMs = 500;
1182
- this.selectedTab = 0;
1183
- // Propriedades para controle do tooltip
1184
- this.hoveredCell = null;
1185
- this.showTooltip = false;
1186
- this.tooltipContent = '';
1187
- this.tooltipPosition = { x: 0, y: 0 };
1188
- this.filtersForm = new FormArray([this.createFilterGroup()]);
1189
- }
1190
- createFilterGroup() {
1191
- return new FormGroup({
1192
- selectFilter: new FormControl(''),
1193
- typeFilter: new FormControl(''),
1194
- selectItem: new FormControl(''),
1195
- initialDate: new FormControl('', this.tableService.dateFormatValidator()),
1196
- finalDate: new FormControl('', this.tableService.dateFormatValidator()),
1197
- });
1198
- }
1199
- addFilter(filterData) {
1200
- const newFilterGroup = this.createFilterGroup();
1201
- if (filterData) {
1202
- if (filterData.selectFilter) {
1203
- newFilterGroup.get('selectFilter')?.setValue(filterData.selectFilter);
1204
- }
1205
- if (filterData.typeFilter) {
1206
- newFilterGroup.get('typeFilter')?.setValue(filterData.typeFilter);
1207
- }
1208
- if (filterData.selectItem) {
1209
- newFilterGroup.get('selectItem')?.setValue(filterData.selectItem);
1210
- }
1211
- if (filterData.initialDate) {
1212
- newFilterGroup.get('initialDate')?.setValue(filterData.initialDate);
1213
- }
1214
- if (filterData.finalDate) {
1215
- newFilterGroup.get('finalDate')?.setValue(filterData.finalDate);
1216
- }
1217
- }
1218
- this.filtersForm.push(newFilterGroup);
1219
- }
1220
- onSelectFilterChange() {
1221
- const lastIndex = this.filtersForm.length - 1;
1222
- const lastFilter = this.filtersForm.at(lastIndex);
1223
- if (lastFilter.get('selectFilter')?.value) {
1224
- this.addFilter();
1225
- }
1226
- }
1227
- removeFilter(index) {
1228
- this.filtersForm.removeAt(index);
1229
- if (this.filtersForm.length === 0) {
1230
- this.addFilter();
1231
- }
1232
- }
1233
- removeAllFilters() {
1234
- this.filtersForm.clear();
1235
- this.addFilter();
1236
- this.resetFilter();
1237
- }
1238
- // METHODS
1239
- async ngOnInit() {
1240
- if (!this.data.color)
1241
- this.data.color = { bg: 'bg-primary', text: 'text-black' };
1242
- this.columnProperties = this.data.displayedColumns.map((column) => {
1243
- return column.property;
1244
- });
1245
- if (this.data.actionButton && !this.data.actionButton.condition) {
1246
- this.data.actionButton.condition = (_row) => true;
1247
- }
1248
- if (this.data.pagination) {
1249
- this.data.displayedColumns.forEach((col) => {
1250
- if (col.isFilterable) {
1251
- if (this.hasFilterableColumn === false)
1252
- this.hasFilterableColumn = true;
1253
- this.dropdownItems.push({
1254
- ...col,
1255
- arrange: 'filter',
1256
- title: col.title,
1257
- });
1258
- }
1259
- if (col.isSortable) {
1260
- if (this.hasSortableColumn === false)
1261
- this.hasSortableColumn = true;
1262
- this.sortableDropdownItems.push({
1263
- ...col,
1264
- arrange: 'ascending',
1265
- title: col.title + ': crescente',
1266
- });
1267
- this.sortableDropdownItems.push({
1268
- ...col,
1269
- arrange: 'descending',
1270
- title: col.title + ': decrescente',
1271
- });
1272
- }
1273
- if (col.isFilterableByDate) {
1274
- this.dropdownItems.push({
1275
- ...col,
1276
- arrange: 'filterByDate',
1277
- title: col.title + ': filtro por data',
1278
- });
1279
- }
1280
- });
1281
- if (this.data.filterableOptions &&
1282
- Array.isArray(this.data.filterableOptions) &&
1283
- this.data.filterableOptions.length > 0) {
1284
- this.data.filterableOptions.forEach((option) => this.dropdownItems.push({ ...option, arrange: 'equals' }));
1285
- }
1286
- }
1287
- // Sem paginação
1288
- if (this.data.pagination === false) {
1289
- await this.loadItems();
1290
- }
1291
- // Com paginação
1292
- if (this.data.pagination === true) {
1293
- if (this.data.sortBy)
1294
- this.sortBy = {
1295
- field: this.data.sortBy.field,
1296
- order: this.data.sortBy.order,
1297
- };
1298
- this.filterSubject
1299
- .pipe(debounceTime(this.debounceTimeMs))
1300
- .subscribe(() => {
1301
- this.loadItemsPaginated('reload', true);
1302
- });
1303
- this.isLoading = true;
1304
- await this.loadItemsPaginated('reload', true);
1305
- this.sort.active = 'createdAt';
1306
- this.sort.direction = 'desc';
1307
- this.dataSource.paginator = this.paginator;
1308
- this.dataSource.sort = this.sort;
1309
- this.totalItems = 0;
1310
- if (this.data.totalRef) {
1311
- for (const totalRef of this.data.totalRef) {
1312
- const totalRefDoc = await totalRef.ref.get();
1313
- const docData = totalRefDoc.data();
1314
- if (docData && docData[totalRef.field])
1315
- this.totalItems = (this.totalItems +
1316
- docData[totalRef.field]);
1317
- }
1318
- }
1319
- this.isLoading = false;
1320
- }
1321
- }
1322
- getDisplayValue(col, row, withinLimit = false) {
1323
- let value;
1324
- if (col.calculateValue) {
1325
- value = col.calculateValue(row);
1326
- }
1327
- else {
1328
- value = this.getNestedValue(row, col.property);
1329
- }
1330
- if (Array.isArray(value) && col.arrayField) {
1331
- value = this.formatArrayValue(value, col.arrayField);
1332
- }
1333
- if (col.queryLength && row[col.property]) {
1334
- value = row[col.property];
1335
- }
1336
- value = col.pipe ? col.pipe.transform(value) : value;
1337
- if (value === null || value === undefined) {
1338
- value = '';
1339
- }
1340
- else {
1341
- value = String(value);
1342
- }
1343
- if (typeof value !== 'string') {
1344
- value = '';
1345
- }
1346
- if (withinLimit || !col.charLimit) {
1347
- return value;
1348
- }
1349
- return value.substring(0, col.charLimit) + '...';
1350
- }
1351
- getNestedValue(obj, path) {
1352
- if (!path)
1353
- return undefined;
1354
- const properties = path.split('.');
1355
- return properties.reduce((acc, currentPart) => acc && acc[currentPart], obj);
1356
- }
1357
- formatArrayValue(array, field) {
1358
- if (!Array.isArray(array) || array.length === 0) {
1359
- return '';
1360
- }
1361
- const values = array
1362
- .map((item) => {
1363
- if (typeof item === 'object' && item !== null) {
1364
- return item[field] || '';
1365
- }
1366
- return String(item);
1367
- })
1368
- .filter((value) => value !== '' && value !== null && value !== undefined);
1369
- return values.join(', ');
1370
- }
1371
- // Métodos sem paginação
1372
- async loadItems() {
1373
- this.items = await this.tableService.getItems(this.data.collectionRef);
1374
- if (this.data.conditions) {
1375
- this.filterItems();
1376
- }
1377
- await this.loadRelations();
1378
- await this.loadQueryLengths();
1379
- this.totalItems = this.items.length;
1380
- this.dataSource = new MatTableDataSource(this.items);
1381
- this.dataSource.paginator = this.paginator;
1382
- this.dataSource.sort = this.sort;
1383
- if (this.data.sortBy) {
1384
- this.dataSource.sort.active = this.data.sortBy.field;
1385
- this.dataSource.sort.direction = this.data.sortBy.order;
1386
- this.dataSource.sort.sortChange.emit();
1387
- }
1388
- this.dataSource.filterPredicate = (data, filter) => {
1389
- return this.data.displayedColumns.some((col) => {
1390
- if (col.filterPredicates) {
1391
- return col.filterPredicates.some((predicate) => {
1392
- const propertyValue = data[col.property];
1393
- if (!propertyValue || typeof propertyValue !== 'object') {
1394
- return false;
1395
- }
1396
- const predicateValue = propertyValue[predicate];
1397
- if (predicateValue === null || predicateValue === undefined) {
1398
- return false;
1399
- }
1400
- return String(predicateValue)
1401
- .trim()
1402
- .toLocaleLowerCase()
1403
- .includes(filter);
1404
- });
1405
- }
1406
- if (col.property && col.isFilterable) {
1407
- const propertyValue = data[col.property];
1408
- if (propertyValue === null || propertyValue === undefined) {
1409
- return false;
1410
- }
1411
- return String(propertyValue)
1412
- .trim()
1413
- .toLocaleLowerCase()
1414
- .includes(filter);
1415
- }
1416
- return false;
1417
- });
1418
- };
1419
- this.filterPredicate = this.dataSource.filterPredicate;
1420
- }
1421
- // Métodos com paginação
1422
- async loadItemsPaginated(navigation = 'reload', reset = false) {
1423
- if (reset && ['forward', 'reload'].includes(navigation)) {
1424
- this.lastDoc = null;
1425
- this.currentClientPageIndex = 0;
1426
- }
1427
- if (reset && ['backward', 'reload'].includes(navigation)) {
1428
- this.firstDoc = null;
1429
- this.currentClientPageIndex = 0;
1430
- }
1431
- const activeFilters = this.filtersForm.controls
1432
- .flatMap((control) => {
1433
- const group = control;
1434
- const selectedFilter = group.get('selectFilter')?.value;
1435
- if (!selectedFilter)
1436
- return [];
1437
- const arrange = selectedFilter.arrange;
1438
- if (arrange === 'filter') {
1439
- const filterValue = group.get('typeFilter')?.value;
1440
- if (!filterValue)
1441
- return [];
1442
- return {
1443
- arrange,
1444
- filter: {
1445
- property: selectedFilter.property,
1446
- filtering: filterValue,
1447
- },
1448
- dateFilter: undefined,
1449
- };
1450
- }
1451
- if (arrange === 'filterByDate') {
1452
- const initial = group.get('initialDate')?.value;
1453
- const final = group.get('finalDate')?.value;
1454
- if (initial && final) {
1455
- const [dayI, monthI, yearI] = initial.split('/');
1456
- const initialDate = new Date(`${monthI}/${dayI}/${yearI}`);
1457
- const [dayF, monthF, yearF] = final.split('/');
1458
- const finalDate = new Date(`${monthF}/${dayF}/${yearF}`);
1459
- finalDate.setHours(23, 59, 59);
1460
- return {
1461
- arrange,
1462
- filter: undefined,
1463
- dateFilter: {
1464
- initial: initialDate,
1465
- final: finalDate,
1466
- },
1467
- };
1468
- }
1469
- return [];
1470
- }
1471
- if (selectedFilter.hasOwnProperty('items') && arrange === 'equals') {
1472
- const selectedItems = group.get('selectItem')?.value;
1473
- if (Array.isArray(selectedItems) && selectedItems.length > 0) {
1474
- return selectedItems.map((item) => ({
1475
- arrange,
1476
- filter: {
1477
- property: item.property,
1478
- filtering: item.value,
1479
- },
1480
- dateFilter: undefined,
1481
- }));
1482
- }
1483
- }
1484
- return [];
1485
- })
1486
- .filter((f) => f && (f.filter?.filtering !== undefined || f.dateFilter));
1487
- this.arrange = {
1488
- filters: activeFilters,
1489
- sortBy: this.sortBy,
1490
- };
1491
- const paginated = {
1492
- batchSize: this.pageSize,
1493
- collection: this.data.collection,
1494
- doc: { lastDoc: this.lastDoc, firstDoc: this.firstDoc },
1495
- navigation,
1496
- arrange: this.arrange,
1497
- conditions: this.data.conditions,
1498
- size: this.totalItems,
1499
- filterFn: this.data.filterFn,
1500
- clientPageIndex: this.currentClientPageIndex,
1501
- };
1502
- const result = await this.tableService.getPaginated(paginated);
1503
- this.items = result.items;
1504
- await this.loadRelations();
1505
- await this.loadQueryLengths();
1506
- this.lastDoc = result.lastDoc;
1507
- this.firstDoc = result.firstDoc;
1508
- // Atualizar currentClientPageIndex se retornado pelo fallback
1509
- if (result.currentClientPageIndex !== undefined) {
1510
- this.currentClientPageIndex = result.currentClientPageIndex;
1511
- }
1512
- let sum = 0;
1513
- if (this.data.totalRef) {
1514
- for (const totalRef of this.data.totalRef) {
1515
- const totalRefDoc = await totalRef.ref.get();
1516
- const docData = totalRefDoc.data();
1517
- if (docData || result.filterLength) {
1518
- sum =
1519
- result.filterLength ??
1520
- (sum + (docData ? docData[totalRef.field] : 0));
1521
- }
1522
- }
1523
- this.totalItems = sum;
1524
- }
1525
- this.hasNextPage = result.hasNextPage;
1526
- this.dataSource = new MatTableDataSource(this.items);
1527
- this.filterPredicate = this.dataSource.filterPredicate;
1528
- }
1529
- async onPageChange(event) {
1530
- if (this.data.pagination === true && event) {
1531
- this.isLoading = true;
1532
- const previousPageIndex = event.previousPageIndex ?? 0;
1533
- const pageIndex = event.pageIndex;
1534
- const currentComponentPageSize = this.pageSize;
1535
- const eventPageSize = event.pageSize;
1536
- const totalItems = this.totalItems;
1537
- let navigationDirection;
1538
- let resetDocs = false;
1539
- let originalPageSize = null;
1540
- const lastPageIndex = Math.max(0, Math.ceil(totalItems / eventPageSize) - 1);
1541
- // Atualizar currentClientPageIndex sempre para o fallback
1542
- this.currentClientPageIndex = pageIndex;
1543
- if (previousPageIndex !== undefined && pageIndex > previousPageIndex) {
1544
- this.currentPageNumber++;
1545
- }
1546
- else if (previousPageIndex !== undefined &&
1547
- pageIndex < previousPageIndex) {
1548
- this.currentPageNumber = Math.max(1, this.currentPageNumber - 1);
1549
- }
1550
- if (eventPageSize !== currentComponentPageSize) {
1551
- console.log('Alterou a quantidade de elementos exibidos por página');
1552
- this.pageSize = eventPageSize;
1553
- navigationDirection = 'forward';
1554
- resetDocs = true;
1555
- this.currentClientPageIndex = 0;
1556
- }
1557
- else if (pageIndex === 0 &&
1558
- previousPageIndex !== undefined &&
1559
- pageIndex < previousPageIndex) {
1560
- console.log('Pulou para a primeira página');
1561
- navigationDirection = 'forward';
1562
- this.currentPageNumber = 1;
1563
- this.currentClientPageIndex = 0;
1564
- resetDocs = true;
1565
- }
1566
- else if (pageIndex === lastPageIndex &&
1567
- previousPageIndex !== undefined &&
1568
- pageIndex > previousPageIndex &&
1569
- pageIndex - previousPageIndex > 1) {
1570
- console.log('Pulou para a ultima página');
1571
- navigationDirection = 'backward';
1572
- resetDocs = true;
1573
- const itemsExpectedInLastPage = totalItems - lastPageIndex * eventPageSize;
1574
- if (itemsExpectedInLastPage > 0 &&
1575
- itemsExpectedInLastPage < eventPageSize) {
1576
- originalPageSize = this.pageSize;
1577
- this.pageSize = itemsExpectedInLastPage;
1578
- }
1579
- }
1580
- else if (previousPageIndex !== undefined &&
1581
- pageIndex > previousPageIndex) {
1582
- console.log('Procedendo');
1583
- navigationDirection = 'forward';
1584
- resetDocs = false;
1585
- }
1586
- else if (previousPageIndex !== undefined &&
1587
- pageIndex < previousPageIndex) {
1588
- console.log('Retrocedendo.');
1589
- navigationDirection = 'backward';
1590
- resetDocs = false;
1591
- }
1592
- else if (previousPageIndex !== undefined &&
1593
- pageIndex === previousPageIndex) {
1594
- console.log('Recarregando.');
1595
- navigationDirection = 'reload';
1596
- resetDocs = false;
1597
- }
1598
- else if (previousPageIndex === undefined && pageIndex === 0) {
1599
- console.log('Evento inicial do paginador para pág 0. ngOnInit carregou.');
1600
- this.isLoading = false;
1601
- if (event)
1602
- this.pageEvent = event;
1603
- return;
1604
- }
1605
- else {
1606
- console.warn('INESPERADO! Condição de navegação não tratada:', event);
1607
- this.isLoading = false;
1608
- if (event)
1609
- this.pageEvent = event;
1610
- return;
1611
- }
1612
- if (navigationDirection) {
1613
- try {
1614
- await this.loadItemsPaginated(navigationDirection, resetDocs);
1615
- }
1616
- catch (error) {
1617
- console.error('Erro ao carregar itens paginados:', error);
1618
- }
1619
- finally {
1620
- if (originalPageSize !== null) {
1621
- this.pageSize = originalPageSize;
1622
- }
1623
- }
1624
- }
1625
- if (event)
1626
- this.pageEvent = event;
1627
- this.isLoading = false;
1628
- }
1629
- }
1630
- // Outros métodos
1631
- applyFilter(value) {
1632
- // Sem paginação
1633
- if (this.data.pagination === false) {
1634
- this.dataSource.filter = String(value).trim().toLowerCase();
1635
- }
1636
- // Com paginação
1637
- if (this.data.pagination === true) {
1638
- this.filterValue = value;
1639
- this.filterSubject.next(this.filterValue);
1640
- }
1641
- }
1642
- goToDetails(row) {
1643
- if (this.data.isNotClickable) {
1644
- return;
1645
- }
1646
- const urlPath = this.data.url || this.data.name;
1647
- const url = this.router.serializeUrl(this.router.createUrlTree([`/${urlPath}`, row.id]));
1648
- window.open(url, '_blank');
1649
- }
1650
- async getRelation(params) {
1651
- try {
1652
- let snapshot;
1653
- if (params.id !== '' &&
1654
- params.id !== undefined &&
1655
- params.collection !== undefined &&
1656
- params.collection !== '') {
1657
- snapshot = await firstValueFrom(this.firestore.collection(params.collection).doc(params.id).get());
1658
- }
1659
- if (snapshot && snapshot.exists) {
1660
- const data = snapshot.data();
1661
- return data?.[params.newProperty] ?? '';
1662
- }
1663
- return '';
1664
- }
1665
- catch (e) {
1666
- console.log(e);
1667
- return '';
1668
- }
1669
- }
1670
- async loadRelations() {
1671
- const relationPromises = this.data.displayedColumns
1672
- .filter((col) => col.relation)
1673
- .flatMap((col) => this.items.map(async (item) => {
1674
- if (col.relation) {
1675
- item[col.property] = await this.getRelation({
1676
- id: item[col.relation.property],
1677
- collection: col.relation.collection,
1678
- newProperty: col.relation.newProperty,
1679
- });
1680
- }
1681
- }));
1682
- await Promise.all(relationPromises);
1683
- }
1684
- async getQueryLength(params) {
1685
- const snapshot = await this.firestore
1686
- .collection(params.relation.collection)
1687
- .ref.where(params.relation.property, params.relation.operator, params.item[params.relation.value])
1688
- .get();
1689
- return snapshot.size;
1690
- }
1691
- async loadQueryLengths() {
1692
- const lengthPromises = this.data.displayedColumns
1693
- .filter((col) => col.queryLength)
1694
- .flatMap((col) => this.items.map(async (item) => {
1695
- if (col.queryLength) {
1696
- item[col.property] = await this.getQueryLength({
1697
- item: item,
1698
- relation: col.queryLength,
1699
- });
1700
- }
1701
- }));
1702
- await Promise.all(lengthPromises);
1703
- }
1704
- filterItems() {
1705
- if (this.data.conditions) {
1706
- this.data.conditions.forEach((cond) => {
1707
- this.items = this.items.filter((item) => {
1708
- const operatorFunction = this.tableService.operators[cond.operator];
1709
- if (operatorFunction) {
1710
- return operatorFunction(item[cond.firestoreProperty], cond.dashProperty);
1711
- }
1712
- return false;
1713
- });
1714
- });
1715
- }
1716
- }
1717
- // Filtro de data
1718
- async search() {
1719
- if (this.selectSort.value) {
1720
- if (this.selectSort.value.arrange === 'ascending') {
1721
- this.sortBy = {
1722
- field: this.selectSort.value.property,
1723
- order: 'asc',
1724
- };
1725
- }
1726
- if (this.selectSort.value.arrange === 'descending') {
1727
- this.sortBy = {
1728
- field: this.selectSort.value.property,
1729
- order: 'desc',
1730
- };
1731
- }
1732
- }
1733
- await this.loadItemsPaginated('reload', true);
1734
- this.currentArrange =
1735
- this.filtersForm.length > 0
1736
- ? this.filtersForm.at(0).get('selectFilter')?.value?.arrange ?? ''
1737
- : '';
1738
- this.paginator.firstPage();
1739
- }
1740
- async resetFilter() {
1741
- if (!this.data.pagination) {
1742
- this.dataSource.filter = '';
1743
- if (this.filterPredicate) {
1744
- this.dataSource.filterPredicate = this.filterPredicate;
1745
- }
1746
- }
1747
- else {
1748
- this.dataSource.filter = '';
1749
- if (this.filterPredicate) {
1750
- this.dataSource.filterPredicate = this.filterPredicate;
1751
- }
1752
- }
1753
- this.filtersForm.clear();
1754
- this.addFilter();
1755
- this.selectSort.patchValue('');
1756
- this.sortBy = {
1757
- order: this.data.sortBy ? this.data.sortBy.order : 'desc',
1758
- field: this.data.sortBy ? this.data.sortBy.field : 'createdAt',
1759
- };
1760
- await this.loadItemsPaginated('reload', true);
1761
- this.currentArrange = '';
1762
- this.paginator.firstPage();
1763
- }
1764
- // Método público para recarregar a tabela
1765
- async reloadTable() {
1766
- if (this.data.pagination) {
1767
- await this.loadItemsPaginated('reload', true);
1768
- this.paginator.firstPage();
1769
- }
1770
- else {
1771
- await this.loadItems();
1772
- }
1773
- }
1774
- updateDisplayedColumns() {
1775
- if (this.dataSource) {
1776
- this.dataSource = new MatTableDataSource([]);
1777
- }
1778
- this.columnProperties = this.data.displayedColumns.map((column) => {
1779
- return column.property;
1780
- });
1781
- this.dropdownItems = [];
1782
- this.sortableDropdownItems = [];
1783
- this.data.displayedColumns.forEach((col) => {
1784
- if (col.isFilterable) {
1785
- this.dropdownItems.push({
1786
- ...col,
1787
- arrange: 'filter',
1788
- title: col.title,
1789
- });
1790
- }
1791
- if (col.isSortable) {
1792
- this.sortableDropdownItems.push({
1793
- ...col,
1794
- arrange: 'ascending',
1795
- title: col.title + ': crescente',
1796
- });
1797
- this.sortableDropdownItems.push({
1798
- ...col,
1799
- arrange: 'descending',
1800
- title: col.title + ': decrescente',
1801
- });
1802
- }
1803
- if (col.isFilterableByDate) {
1804
- this.dropdownItems.push({
1805
- ...col,
1806
- arrange: 'filterByDate',
1807
- title: col.title + ': filtro por data',
1808
- });
1809
- }
1810
- });
1811
- if (this.data.filterableOptions &&
1812
- Array.isArray(this.data.filterableOptions)) {
1813
- this.data.filterableOptions.forEach((option) => this.dropdownItems.push({ ...option, arrange: 'equals' }));
1814
- }
1815
- }
1816
- isString(value) {
1817
- return typeof value === 'string';
1818
- }
1819
- // Métodos para controle do tooltip
1820
- onCellMouseEnter(event, row, col) {
1821
- // Só mostrar tooltip se a coluna tiver charLimit definido
1822
- if (!col.charLimit) {
1823
- return;
1824
- }
1825
- const fullValue = this.getDisplayValue(col, row, true);
1826
- // Só mostrar tooltip se o valor completo for maior que o limite
1827
- if (fullValue.length <= col.charLimit) {
1828
- return;
1829
- }
1830
- this.hoveredCell = { row, col };
1831
- this.tooltipContent = fullValue;
1832
- // Definir posição do tooltip
1833
- this.tooltipPosition = {
1834
- x: event.clientX + 10,
1835
- y: event.clientY - 10,
1836
- };
1837
- // Timeout para mostrar o tooltip
1838
- this.tooltipTimeout = setTimeout(() => {
1839
- if (this.hoveredCell &&
1840
- this.hoveredCell.row === row &&
1841
- this.hoveredCell.col === col) {
1842
- this.showTooltip = true;
1843
- }
1844
- }, 500);
1845
- }
1846
- onCellMouseLeave() {
1847
- if (this.tooltipTimeout) {
1848
- clearTimeout(this.tooltipTimeout);
1849
- this.tooltipTimeout = null;
1850
- }
1851
- this.showTooltip = false;
1852
- this.hoveredCell = null;
1853
- this.tooltipContent = '';
1854
- }
1855
- onCellMouseMove(event) {
1856
- if (this.showTooltip) {
1857
- this.tooltipPosition = {
1858
- x: event.clientX + 10,
1859
- y: event.clientY - 10,
1860
- };
1861
- }
1862
- }
1863
- // Métodos para inversão vertical dos tabs
1864
- getTabGroups(tabs) {
1865
- if (!tabs || tabs.length === 0)
1866
- return [];
1867
- const totalGroups = Math.ceil(tabs.length / 6);
1868
- const groups = [];
1869
- // Criar array de índices invertidos (último grupo primeiro)
1870
- for (let i = totalGroups - 1; i >= 0; i--) {
1871
- groups.push(i);
1872
- }
1873
- return groups;
1874
- }
1875
- getTabGroup(tabs, groupIndex) {
1876
- if (!tabs || tabs.length === 0)
1877
- return [];
1878
- const startIndex = groupIndex * 6;
1879
- const endIndex = Math.min(startIndex + 6, tabs.length);
1880
- return tabs.slice(startIndex, endIndex);
1881
- }
1882
- getRealTabIndex(groupIndex, tabIndexInGroup) {
1883
- if (!this.data.tabs?.tabsData)
1884
- return 0;
1885
- const totalGroups = Math.ceil(this.data.tabs.tabsData.length / 6);
1886
- const realGroupIndex = totalGroups - 1 - groupIndex;
1887
- return realGroupIndex * 6 + tabIndexInGroup;
1888
- }
1889
- onTableSelected(i, j) {
1890
- if (!this.data.tabs?.tabsData || !this.data.tabs.method)
1891
- return;
1892
- this.selectedTab = this.getRealTabIndex(i, j);
1893
- const tab = this.data.tabs.tabsData[this.selectedTab];
1894
- if (tab) {
1895
- this.data.tabs.method(tab, this.selectedTab);
1896
- }
1897
- }
1898
- isTabSelected(originalIndex) {
1899
- return this.selectedTab === originalIndex;
1900
- }
1901
- shouldShowActionButton() {
1902
- if (!this.data?.actionButton) {
1903
- return false;
1904
- }
1905
- if (!this.data.actionButton.condition) {
1906
- return true;
1907
- }
1908
- try {
1909
- return this.data.actionButton.condition(null) ?? true;
1910
- }
1911
- catch {
1912
- return true;
1913
- }
1914
- }
1915
- }
1916
- TableComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: TableComponent, deps: [{ token: i1$1.Router }, { token: TableService }, { token: i1.AngularFirestore }], target: i0.ɵɵFactoryTarget.Component });
1917
- TableComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.2.10", type: TableComponent, selector: "lib-table", inputs: { data: "data", downloadTable: "downloadTable" }, viewQueries: [{ propertyName: "paginator", first: true, predicate: MatPaginator, descendants: true }, { propertyName: "sort", first: true, predicate: MatSort, descendants: true }], ngImport: i0, template: "<div *ngIf=\"data\" class=\"card-body\">\n <div class=\"flex flex-col justify-between gap-6\">\n <!-- UNIFIED CONTROL PANEL: FILTERS, SORT & ACTIONS -->\n <div\n class=\"rounded-xl border border-gray-200 bg-white p-4 shadow-lg\"\n *ngIf=\"\n data.pagination === true &&\n (dropdownItems.length > 0 ||\n sortableDropdownItems.length > 0 ||\n data.actionButton)\n \"\n >\n <!-- PANEL HEADER: Title, Custom Action, and Global Actions -->\n <div\n class=\"mb-4 flex flex-col items-start justify-between gap-4 border-b-2 border-gray-200 pb-4 md:flex-row md:items-center\"\n >\n <!-- Left Side: Title & Main Action Button -->\n <div class=\"flex flex-wrap items-center gap-4\">\n <div class=\"flex items-center gap-2\">\n <i class=\"fa fa-filter text-xl text-blue-500\"></i>\n <span class=\"text-lg font-semibold text-gray-700\"\n >Filtros e A\u00E7\u00F5es</span\n >\n </div>\n <button\n *ngIf=\"data.actionButton && data.actionButton.condition\"\n [ngClass]=\"\n (data.actionButton.colorClass || 'bg-blue-500') +\n ' flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium text-white hover:opacity-70'\n \"\n [routerLink]=\"data.actionButton.routerLink\"\n (click)=\"\n data.actionButton.method ? data.actionButton.method($event) : null\n \"\n >\n <i\n *ngIf=\"data.actionButton.icon\"\n [class]=\"data.actionButton.icon\"\n ></i>\n {{ data.actionButton.label }}\n </button>\n </div>\n\n <!-- Right Side: Search, Reset, Export -->\n <div\n class=\"flex flex-wrap gap-3\"\n *ngIf=\"\n this.hasFilterableColumn === true || this.hasSortableColumn === true\n \"\n >\n <button\n (click)=\"search()\"\n type=\"button\"\n class=\"flex items-center gap-2 rounded-lg bg-green-600 px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-green-700\"\n matTooltip=\"Aplicar filtros\"\n >\n <i class=\"fa fa-search\"></i>\n Pesquisar\n </button>\n\n <button\n (click)=\"resetFilter()\"\n class=\"flex items-center gap-2 rounded-lg bg-red-500 px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-red-600\"\n matTooltip=\"Limpar filtros\"\n >\n <i class=\"fas fa-redo-alt\"></i>\n Resetar\n </button>\n\n <button\n *ngIf=\"data.download !== false && downloadTable\"\n class=\"flex items-center gap-2 rounded-lg bg-orange-500 px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-orange-600\"\n matTooltipPosition=\"above\"\n matTooltip=\"Exportar Tabela\"\n [disabled]=\"\n this.dataSource && this.dataSource.filteredData.length <= 0\n \"\n (click)=\"\n $any(arrange) && downloadTable !== undefined\n ? downloadTable($any(arrange), data.conditions || [])\n : null\n \"\n >\n <i class=\"fa fa-download\"></i>\n Exportar\n </button>\n </div>\n </div>\n\n <!-- FILTERS CONTENT (WITH REFINEMENTS) -->\n <div class=\"mb-4 space-y-3\" *ngIf=\"filtersForm.controls.length > 0\">\n <div\n [formGroup]=\"$any(filterGroup)\"\n *ngFor=\"let filterGroup of filtersForm.controls; let i = index\"\n class=\"flex flex-wrap items-center gap-3 rounded-lg border border-gray-200 p-2\"\n >\n <!-- FILTER TYPE SELECTOR -->\n <div class=\"min-w-[200px] flex-1\" *ngIf=\"dropdownItems.length > 0\">\n <mat-form-field appearance=\"outline\" class=\"w-full\">\n <mat-label>Tipo de filtro</mat-label>\n <mat-select\n placeholder=\"Selecione o tipo...\"\n formControlName=\"selectFilter\"\n (selectionChange)=\"onSelectFilterChange()\"\n >\n <mat-option *ngFor=\"let item of dropdownItems\" [value]=\"item\">\n <div class=\"flex items-center gap-2\">\n <i\n [class]=\"item.icon || 'fa fa-filter'\"\n class=\"text-sm text-blue-500\"\n ></i>\n <span>{{ item.title }}</span>\n </div>\n </mat-option>\n </mat-select>\n </mat-form-field>\n </div>\n\n <!-- TEXT FILTER -->\n <div\n class=\"min-w-[200px] flex-1\"\n *ngIf=\"\n $any(filterGroup).get('selectFilter')?.value?.arrange === 'filter'\n \"\n >\n <mat-form-field appearance=\"outline\" class=\"w-full\">\n <mat-label class=\"flex items-center gap-2\">\n <i class=\"fa fa-search text-gray-400\"></i>\n <span>{{\n $any(filterGroup).get(\"selectFilter\")?.value?.title ||\n \"Filtrar\"\n }}</span>\n </mat-label>\n <input\n (keyup.enter)=\"search()\"\n formControlName=\"typeFilter\"\n matInput\n placeholder=\"Digite para filtrar...\"\n #input\n />\n </mat-form-field>\n </div>\n\n <!-- DROPDOWN FILTER -->\n <div\n class=\"min-w-[200px] flex-1\"\n *ngIf=\"\n $any(filterGroup).get('selectFilter')?.value &&\n $any(filterGroup)\n .get('selectFilter')\n ?.value.hasOwnProperty('items')\n \"\n >\n <mat-form-field appearance=\"outline\" class=\"w-full\">\n <mat-label>{{\n $any(filterGroup).get(\"selectFilter\")?.value?.title ||\n \"Selecione\"\n }}</mat-label>\n <mat-select\n placeholder=\"Selecione...\"\n formControlName=\"selectItem\"\n multiple\n >\n <mat-option\n *ngFor=\"\n let item of $any(filterGroup).get('selectFilter')?.value\n .items\n \"\n [value]=\"item\"\n >\n {{ item.label }}\n </mat-option>\n </mat-select>\n </mat-form-field>\n </div>\n\n <!-- DATE FILTER -->\n <div\n class=\"min-w-[340px] flex-auto\"\n *ngIf=\"\n $any(filterGroup).get('selectFilter')?.value?.arrange ===\n 'filterByDate'\n \"\n >\n <div\n class=\"flex flex-col items-stretch gap-3 sm:flex-row sm:items-center\"\n >\n <mat-form-field appearance=\"outline\" class=\"flex-1\">\n <mat-label class=\"flex items-center gap-2\">\n <i class=\"fa fa-calendar text-gray-400\"></i>\n <span>Data Inicial</span>\n </mat-label>\n <input\n matInput\n (keyup.enter)=\"search()\"\n formControlName=\"initialDate\"\n [dropSpecialCharacters]=\"false\"\n mask=\"d0/M0/0000\"\n placeholder=\"DD/MM/AAAA\"\n maxlength=\"10\"\n />\n </mat-form-field>\n\n <mat-form-field appearance=\"outline\" class=\"flex-1\">\n <mat-label class=\"flex items-center gap-2\">\n <i class=\"fa fa-calendar text-gray-400\"></i>\n <span>Data Final</span>\n </mat-label>\n <input\n (keyup.enter)=\"search()\"\n matInput\n formControlName=\"finalDate\"\n [dropSpecialCharacters]=\"false\"\n mask=\"d0/M0/0000\"\n placeholder=\"DD/MM/AAAA\"\n maxlength=\"10\"\n />\n </mat-form-field>\n </div>\n </div>\n\n <!-- REMOVE FILTER BUTTON -->\n <div *ngIf=\"filtersForm.length > 1\" class=\"ml-auto flex-shrink-0\">\n <button\n (click)=\"removeFilter(i)\"\n class=\"flex h-10 w-10 items-center justify-center rounded-full transition-colors duration-300 hover:bg-red-100\"\n matTooltip=\"Remover filtro\"\n >\n <i class=\"fa fa-trash text-red-500 hover:text-red-600\"></i>\n </button>\n </div>\n </div>\n </div>\n\n <!-- PANEL FOOTER: Add Filter & Sort -->\n <div\n class=\"-mb-2 flex flex-col items-center justify-between gap-4 border-t border-gray-200 pt-4 sm:flex-row\"\n >\n <!-- Add Filter Button -->\n <div *ngIf=\"dropdownItems.length > 0\">\n <button\n (click)=\"addFilter()\"\n class=\"transform rounded-full border-2 border-blue-300 bg-blue-50 px-6 py-2 text-sm font-medium text-blue-600 transition-all duration-300 hover:-translate-y-0.5 hover:border-blue-400 hover:bg-blue-100 hover:shadow-md\"\n matTooltip=\"Adicionar novo filtro\"\n >\n <i class=\"fa fa-plus mr-2\"></i>\n Adicionar Filtro\n </button>\n </div>\n\n <!-- Sort Dropdown -->\n <div\n class=\"w-full sm:w-auto sm:min-w-[250px]\"\n *ngIf=\"sortableDropdownItems.length > 0\"\n >\n <mat-form-field appearance=\"outline\" class=\"w-full\">\n <mat-label>Ordenar por</mat-label>\n <mat-select placeholder=\"Selecione...\" [formControl]=\"selectSort\">\n <mat-option\n *ngFor=\"let item of sortableDropdownItems\"\n [value]=\"item\"\n >\n <div class=\"flex items-center gap-2\">\n <i class=\"fa fa-sort-alpha-down text-cyan-600\"></i>\n <span>{{ item.title }}</span>\n </div>\n </mat-option>\n </mat-select>\n </mat-form-field>\n </div>\n </div>\n </div>\n\n <!-- SIMPLE SEARCH (for non-paginated tables) -->\n <div\n class=\"rounded-xl border border-gray-200 bg-white p-4 shadow-lg\"\n *ngIf=\"data.pagination === false\"\n >\n <mat-form-field appearance=\"outline\" class=\"w-full\">\n <mat-label class=\"flex items-center gap-2\">\n <i class=\"fa fa-search text-blue-500\"></i>\n Buscar\n </mat-label>\n <input\n matInput\n (keyup.enter)=\"search()\"\n (keyup)=\"applyFilter(filterInput.value)\"\n placeholder=\"Digite para filtrar...\"\n #filterInput\n />\n <mat-icon matSuffix class=\"text-gray-500\">search</mat-icon>\n </mat-form-field>\n <button\n *ngIf=\"data.actionButton\"\n [ngClass]=\"\n (data.actionButton.colorClass || 'bg-blue-500') +\n ' float-right flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium text-white hover:opacity-70'\n \"\n [routerLink]=\"data.actionButton.routerLink\"\n (click)=\"\n data.actionButton.method ? data.actionButton.method($event) : null\n \"\n >\n <i *ngIf=\"data.actionButton.icon\" [class]=\"data.actionButton.icon\"></i>\n {{ data.actionButton.label }}\n </button>\n </div>\n\n <div class=\"flex flex-col\">\n <div\n class=\"mx-auto flex flex-col\"\n *ngIf=\"data.tabs && data.tabs.tabsData && data.tabs.tabsData.length > 0\"\n >\n <!-- Calcular quantos grupos de 6 tabs existem -->\n <ng-container\n *ngFor=\"\n let groupIndex of getTabGroups(data.tabs.tabsData);\n let i = index\n \"\n >\n <div class=\"mx-auto flex flex-row\">\n <ng-container\n *ngFor=\"\n let tab of getTabGroup(data.tabs.tabsData, groupIndex);\n let j = index\n \"\n >\n <button\n class=\"border-2 border-gray-300 bg-gray-200 px-4 py-2 font-medium transition hover:brightness-95\"\n [ngClass]=\"\n isTabSelected(getRealTabIndex(i, j))\n ? 'border-b-0 brightness-110'\n : ''\n \"\n (click)=\"onTableSelected(i, j)\"\n >\n {{ tab.label }}\n <span\n *ngIf=\"tab.counter !== undefined\"\n class=\"ml-2 text-xs font-bold\"\n [ngClass]=\"tab.counterClass\"\n >\n {{ tab.counter }}\n </span>\n </button>\n </ng-container>\n </div>\n </ng-container>\n </div>\n <div class=\"mat-elevation-z8 w-full overflow-x-auto rounded-xl\">\n <table\n mat-table\n [dataSource]=\"dataSource\"\n matSort\n #sort=\"matSort\"\n matSortActive=\"createdAt\"\n matSortDirection=\"desc\"\n >\n <ng-container\n *ngFor=\"let col of data.displayedColumns\"\n matColumnDef=\"{{ col.property }}\"\n >\n <ng-container *matHeaderCellDef>\n <!-- IF THE COLUMN IS NOT SORTABLE, THEN DON'T SHOW THE SORT BUTTONS -->\n <th\n *ngIf=\"!col.isSortable || data.pagination === true\"\n mat-header-cell\n [ngClass]=\"\n (data?.color?.bg ? ' ' + $any(data.color).bg : '') +\n (data?.color?.text ? ' ' + $any(data.color).text : '')\n \"\n >\n {{ col.title }}\n </th>\n <!-- IF THE COLUMN IS SORTABLE, THEN SHOW THE SORT BUTTONS -->\n <th\n *ngIf=\"col.isSortable && data.pagination === false\"\n mat-header-cell\n mat-sort-header\n [ngClass]=\"\n (data?.color?.bg ? ' ' + $any(data.color).bg : '') +\n (data?.color?.text ? ' ' + $any(data.color).text : '')\n \"\n >\n {{ col.title }}\n </th>\n <td\n mat-cell\n *matCellDef=\"let row\"\n (click)=\"col.method ? col.method(row) : null\"\n (mouseenter)=\"onCellMouseEnter($event, row, col)\"\n (mouseleave)=\"onCellMouseLeave()\"\n (mousemove)=\"onCellMouseMove($event)\"\n >\n <!-- CHECK IF THE COLUMN MUST BE DISPLAYED -->\n <span *ngIf=\"!col.image && !col.iconClass && !col.method\">\n <ng-container>\n <span\n *ngIf=\"\n col.charLimit &&\n row[col.property] &&\n row[col.property].length > col.charLimit;\n else withinLimit\n \"\n >\n <a\n *ngIf=\"col.hasLink === true\"\n [href]=\"row[col.property]\"\n target=\"_blank\"\n >\n {{ getDisplayValue(col, row) }}\n </a>\n <a\n *ngIf=\"col.hasLink && isString(col.hasLink)\"\n [href]=\"col.hasLink\"\n target=\"_blank\"\n >\n {{ getDisplayValue(col, row) }}\n </a>\n <span\n *ngIf=\"col.hasLink !== true && !isString(col.hasLink)\"\n >\n {{ getDisplayValue(col, row) }}\n </span>\n </span>\n </ng-container>\n <ng-template #withinLimit>\n <a\n *ngIf=\"col.hasLink === true\"\n [href]=\"row[col.property]\"\n target=\"_blank\"\n >\n {{ getDisplayValue(col, row, true) }}\n </a>\n <a\n *ngIf=\"col.hasLink && isString(col.hasLink)\"\n [href]=\"col.hasLink\"\n target=\"_blank\"\n >\n {{ getDisplayValue(col, row, true) }}\n </a>\n <span\n *ngIf=\"col.hasLink !== true && !isString(col.hasLink)\"\n >\n {{ getDisplayValue(col, row, true) }}\n </span>\n </ng-template>\n </span>\n <!------------------- IMAGE ------------------>\n <img\n *ngIf=\"\n col.image && col.image.path && !col.iconClass && !col.method\n \"\n [src]=\"col.image.path + '/' + row[col.property]\"\n [ngClass]=\"col.image.class\"\n alt=\"Imagem\"\n />\n <img\n *ngIf=\"\n col.image && col.image.url && !col.iconClass && !col.method\n \"\n [src]=\"row[col.property]\"\n [ngClass]=\"col.image.class\"\n alt=\"Imagem\"\n />\n <ng-container *ngIf=\"col.iconClass\">\n <button\n *ngFor=\"let iconClass of col.iconClass\"\n (click)=\"\n iconClass.buttonMethod\n ? iconClass.buttonMethod(row, $event)\n : $event.stopPropagation()\n \"\n >\n <span\n [ngClass]=\"iconClass.class\"\n *ngIf=\"\n iconClass.condition === undefined ||\n (iconClass.condition !== undefined &&\n $any(iconClass.condition)(row))\n \"\n >{{ iconClass.text }}</span\n >\n </button>\n </ng-container>\n </td>\n </ng-container>\n </ng-container>\n\n <tr mat-header-row *matHeaderRowDef=\"columnProperties\"></tr>\n <tr\n [ngClass]=\"{\n 'example-element-row': data.isNotClickable === true,\n 'example-element-row cursor-pointer': !data.isNotClickable\n }\"\n mat-row\n *matRowDef=\"let row; columns: columnProperties\"\n (click)=\"goToDetails(row)\"\n ></tr>\n\n <!-- ROW SHOWN WHEN THERE IS NO MATCHING DATA. -->\n <tr class=\"mat-row\" *matNoDataRow>\n <td *ngIf=\"!isLoading\" class=\"mat-cell p-4\" colspan=\"4\">\n Nenhum resultado encontrado para a busca\n </td>\n </tr>\n </table>\n\n <div class=\"flex justify-center\" *ngIf=\"isLoading\">\n <mat-spinner></mat-spinner>\n </div>\n\n <div class=\"paginator-container\">\n <mat-paginator\n #paginator\n [pageSizeOptions]=\"[25, 50, 100]\"\n [pageSize]=\"pageSize\"\n [length]=\"totalItems\"\n showFirstLastButtons\n aria-label=\"Select page of periodic elements\"\n (page)=\"onPageChange($event)\"\n [ngClass]=\"{\n 'hide-length':\n ['filter', 'filterByDate', 'equals'].includes(\n this.currentArrange\n ) || this.data.filterFn,\n 'hide-next-button': !hasNextPage && data.pagination === true,\n 'hide-last-button':\n (!hasNextPage && data.pagination === true) || this.data.filterFn\n }\"\n >\n </mat-paginator>\n <div\n *ngIf=\"\n !isLoading &&\n dataSource?.data &&\n dataSource.data.length > 0 &&\n data?.filterFn\n \"\n class=\"page-number-display\"\n >\n {{ currentPageNumber }}\n </div>\n </div>\n </div>\n </div>\n </div>\n\n <!-- TOOLTIP PERSONALIZADO -->\n <div\n *ngIf=\"showTooltip\"\n class=\"fixed z-50 max-w-md break-words rounded-lg bg-gray-800 px-3 py-2 text-sm text-white shadow-lg\"\n [style.left.px]=\"tooltipPosition.x\"\n [style.top.px]=\"tooltipPosition.y\"\n [style.pointer-events]=\"'none'\"\n >\n {{ tooltipContent }}\n </div>\n</div>\n", styles: ["::ng-deep .hide-length .mat-mdc-paginator-range-label{display:none}::ng-deep .hide-next-button .mat-mdc-tooltip-trigger.mat-mdc-paginator-navigation-next.mdc-icon-button.mat-mdc-icon-button.mat-unthemed.mat-mdc-button-base{visibility:hidden}::ng-deep .hide-next-button .mat-mdc-tooltip-trigger.mat-mdc-paginator-navigation-last.mdc-icon-button.mat-mdc-icon-button.mat-unthemed.mat-mdc-button-base.ng-star-inserted{visibility:hidden}::ng-deep .mat-mdc-text-field-wrapper.mdc-text-field.ng-tns-c162-1.mdc-text-field--filled{width:25dvw}::ng-deep .custom-filter .mat-mdc-text-field-wrapper{width:20dvw;max-width:300px}\n"], dependencies: [{ kind: "directive", type: i4.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "directive", type: i4.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "directive", type: i4.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i5.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i5.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i5.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i5.MaxLengthValidator, selector: "[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]", inputs: ["maxlength"] }, { kind: "directive", type: i5.FormControlDirective, selector: "[formControl]", inputs: ["formControl", "disabled", "ngModel"], outputs: ["ngModelChange"], exportAs: ["ngForm"] }, { kind: "directive", type: i5.FormGroupDirective, selector: "[formGroup]", inputs: ["formGroup"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "directive", type: i5.FormControlName, selector: "[formControlName]", inputs: ["formControlName", "disabled", "ngModel"], outputs: ["ngModelChange"] }, { kind: "directive", type: i1$1.RouterLink, selector: "[routerLink]", inputs: ["target", "queryParams", "fragment", "queryParamsHandling", "state", "relativeTo", "preserveFragment", "skipLocationChange", "replaceUrl", "routerLink"] }, { kind: "component", type: i6.MatTable, selector: "mat-table, table[mat-table]", exportAs: ["matTable"] }, { kind: "directive", type: i6.MatHeaderCellDef, selector: "[matHeaderCellDef]" }, { kind: "directive", type: i6.MatHeaderRowDef, selector: "[matHeaderRowDef]", inputs: ["matHeaderRowDef", "matHeaderRowDefSticky"] }, { kind: "directive", type: i6.MatColumnDef, selector: "[matColumnDef]", inputs: ["sticky", "matColumnDef"] }, { kind: "directive", type: i6.MatCellDef, selector: "[matCellDef]" }, { kind: "directive", type: i6.MatRowDef, selector: "[matRowDef]", inputs: ["matRowDefColumns", "matRowDefWhen"] }, { kind: "directive", type: i6.MatHeaderCell, selector: "mat-header-cell, th[mat-header-cell]" }, { kind: "directive", type: i6.MatCell, selector: "mat-cell, td[mat-cell]" }, { kind: "component", type: i6.MatHeaderRow, selector: "mat-header-row, tr[mat-header-row]", exportAs: ["matHeaderRow"] }, { kind: "component", type: i6.MatRow, selector: "mat-row, tr[mat-row]", exportAs: ["matRow"] }, { kind: "directive", type: i6.MatNoDataRow, selector: "ng-template[matNoDataRow]" }, { kind: "component", type: i7.MatPaginator, selector: "mat-paginator", inputs: ["disabled"], exportAs: ["matPaginator"] }, { kind: "directive", type: i8.MatSort, selector: "[matSort]", inputs: ["matSortDisabled", "matSortActive", "matSortStart", "matSortDirection", "matSortDisableClear"], outputs: ["matSortChange"], exportAs: ["matSort"] }, { kind: "component", type: i8.MatSortHeader, selector: "[mat-sort-header]", inputs: ["disabled", "mat-sort-header", "arrowPosition", "start", "sortActionDescription", "disableClear"], exportAs: ["matSortHeader"] }, { kind: "component", type: i9.MatFormField, selector: "mat-form-field", inputs: ["hideRequiredMarker", "color", "floatLabel", "appearance", "subscriptSizing", "hintLabel"], exportAs: ["matFormField"] }, { kind: "directive", type: i9.MatLabel, selector: "mat-label" }, { kind: "directive", type: i9.MatSuffix, selector: "[matSuffix], [matIconSuffix], [matTextSuffix]", inputs: ["matTextSuffix"] }, { kind: "directive", type: i10.MatInput, selector: "input[matInput], textarea[matInput], select[matNativeControl], input[matNativeControl], textarea[matNativeControl]", inputs: ["disabled", "id", "placeholder", "name", "required", "type", "errorStateMatcher", "aria-describedby", "value", "readonly"], exportAs: ["matInput"] }, { kind: "component", type: i11.MatSelect, selector: "mat-select", inputs: ["disabled", "disableRipple", "tabIndex", "hideSingleSelectionIndicator"], exportAs: ["matSelect"] }, { kind: "component", type: i12.MatOption, selector: "mat-option", exportAs: ["matOption"] }, { kind: "directive", type: i13.MatTooltip, selector: "[matTooltip]", exportAs: ["matTooltip"] }, { kind: "component", type: i14.MatProgressSpinner, selector: "mat-progress-spinner, mat-spinner", inputs: ["color", "mode", "value", "diameter", "strokeWidth"], exportAs: ["matProgressSpinner"] }, { kind: "component", type: i15.MatIcon, selector: "mat-icon", inputs: ["color", "inline", "svgIcon", "fontSet", "fontIcon"], exportAs: ["matIcon"] }, { kind: "directive", type: i16.NgxMaskDirective, selector: "input[mask], textarea[mask]", inputs: ["mask", "specialCharacters", "patterns", "prefix", "suffix", "thousandSeparator", "decimalMarker", "dropSpecialCharacters", "hiddenInput", "showMaskTyped", "placeHolderCharacter", "shownMaskExpression", "showTemplate", "clearIfNotMatch", "validation", "separatorLimit", "allowNegativeNumbers", "leadZeroDateTime", "leadZero", "triggerOnMaskChange", "apm", "inputTransformFn", "outputTransformFn", "keepCharacterPositions"], outputs: ["maskFilled"], exportAs: ["mask", "ngxMask"] }] });
1918
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: TableComponent, decorators: [{
1919
- type: Component,
1920
- args: [{ selector: 'lib-table', template: "<div *ngIf=\"data\" class=\"card-body\">\n <div class=\"flex flex-col justify-between gap-6\">\n <!-- UNIFIED CONTROL PANEL: FILTERS, SORT & ACTIONS -->\n <div\n class=\"rounded-xl border border-gray-200 bg-white p-4 shadow-lg\"\n *ngIf=\"\n data.pagination === true &&\n (dropdownItems.length > 0 ||\n sortableDropdownItems.length > 0 ||\n data.actionButton)\n \"\n >\n <!-- PANEL HEADER: Title, Custom Action, and Global Actions -->\n <div\n class=\"mb-4 flex flex-col items-start justify-between gap-4 border-b-2 border-gray-200 pb-4 md:flex-row md:items-center\"\n >\n <!-- Left Side: Title & Main Action Button -->\n <div class=\"flex flex-wrap items-center gap-4\">\n <div class=\"flex items-center gap-2\">\n <i class=\"fa fa-filter text-xl text-blue-500\"></i>\n <span class=\"text-lg font-semibold text-gray-700\"\n >Filtros e A\u00E7\u00F5es</span\n >\n </div>\n <button\n *ngIf=\"data.actionButton && data.actionButton.condition\"\n [ngClass]=\"\n (data.actionButton.colorClass || 'bg-blue-500') +\n ' flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium text-white hover:opacity-70'\n \"\n [routerLink]=\"data.actionButton.routerLink\"\n (click)=\"\n data.actionButton.method ? data.actionButton.method($event) : null\n \"\n >\n <i\n *ngIf=\"data.actionButton.icon\"\n [class]=\"data.actionButton.icon\"\n ></i>\n {{ data.actionButton.label }}\n </button>\n </div>\n\n <!-- Right Side: Search, Reset, Export -->\n <div\n class=\"flex flex-wrap gap-3\"\n *ngIf=\"\n this.hasFilterableColumn === true || this.hasSortableColumn === true\n \"\n >\n <button\n (click)=\"search()\"\n type=\"button\"\n class=\"flex items-center gap-2 rounded-lg bg-green-600 px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-green-700\"\n matTooltip=\"Aplicar filtros\"\n >\n <i class=\"fa fa-search\"></i>\n Pesquisar\n </button>\n\n <button\n (click)=\"resetFilter()\"\n class=\"flex items-center gap-2 rounded-lg bg-red-500 px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-red-600\"\n matTooltip=\"Limpar filtros\"\n >\n <i class=\"fas fa-redo-alt\"></i>\n Resetar\n </button>\n\n <button\n *ngIf=\"data.download !== false && downloadTable\"\n class=\"flex items-center gap-2 rounded-lg bg-orange-500 px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-orange-600\"\n matTooltipPosition=\"above\"\n matTooltip=\"Exportar Tabela\"\n [disabled]=\"\n this.dataSource && this.dataSource.filteredData.length <= 0\n \"\n (click)=\"\n $any(arrange) && downloadTable !== undefined\n ? downloadTable($any(arrange), data.conditions || [])\n : null\n \"\n >\n <i class=\"fa fa-download\"></i>\n Exportar\n </button>\n </div>\n </div>\n\n <!-- FILTERS CONTENT (WITH REFINEMENTS) -->\n <div class=\"mb-4 space-y-3\" *ngIf=\"filtersForm.controls.length > 0\">\n <div\n [formGroup]=\"$any(filterGroup)\"\n *ngFor=\"let filterGroup of filtersForm.controls; let i = index\"\n class=\"flex flex-wrap items-center gap-3 rounded-lg border border-gray-200 p-2\"\n >\n <!-- FILTER TYPE SELECTOR -->\n <div class=\"min-w-[200px] flex-1\" *ngIf=\"dropdownItems.length > 0\">\n <mat-form-field appearance=\"outline\" class=\"w-full\">\n <mat-label>Tipo de filtro</mat-label>\n <mat-select\n placeholder=\"Selecione o tipo...\"\n formControlName=\"selectFilter\"\n (selectionChange)=\"onSelectFilterChange()\"\n >\n <mat-option *ngFor=\"let item of dropdownItems\" [value]=\"item\">\n <div class=\"flex items-center gap-2\">\n <i\n [class]=\"item.icon || 'fa fa-filter'\"\n class=\"text-sm text-blue-500\"\n ></i>\n <span>{{ item.title }}</span>\n </div>\n </mat-option>\n </mat-select>\n </mat-form-field>\n </div>\n\n <!-- TEXT FILTER -->\n <div\n class=\"min-w-[200px] flex-1\"\n *ngIf=\"\n $any(filterGroup).get('selectFilter')?.value?.arrange === 'filter'\n \"\n >\n <mat-form-field appearance=\"outline\" class=\"w-full\">\n <mat-label class=\"flex items-center gap-2\">\n <i class=\"fa fa-search text-gray-400\"></i>\n <span>{{\n $any(filterGroup).get(\"selectFilter\")?.value?.title ||\n \"Filtrar\"\n }}</span>\n </mat-label>\n <input\n (keyup.enter)=\"search()\"\n formControlName=\"typeFilter\"\n matInput\n placeholder=\"Digite para filtrar...\"\n #input\n />\n </mat-form-field>\n </div>\n\n <!-- DROPDOWN FILTER -->\n <div\n class=\"min-w-[200px] flex-1\"\n *ngIf=\"\n $any(filterGroup).get('selectFilter')?.value &&\n $any(filterGroup)\n .get('selectFilter')\n ?.value.hasOwnProperty('items')\n \"\n >\n <mat-form-field appearance=\"outline\" class=\"w-full\">\n <mat-label>{{\n $any(filterGroup).get(\"selectFilter\")?.value?.title ||\n \"Selecione\"\n }}</mat-label>\n <mat-select\n placeholder=\"Selecione...\"\n formControlName=\"selectItem\"\n multiple\n >\n <mat-option\n *ngFor=\"\n let item of $any(filterGroup).get('selectFilter')?.value\n .items\n \"\n [value]=\"item\"\n >\n {{ item.label }}\n </mat-option>\n </mat-select>\n </mat-form-field>\n </div>\n\n <!-- DATE FILTER -->\n <div\n class=\"min-w-[340px] flex-auto\"\n *ngIf=\"\n $any(filterGroup).get('selectFilter')?.value?.arrange ===\n 'filterByDate'\n \"\n >\n <div\n class=\"flex flex-col items-stretch gap-3 sm:flex-row sm:items-center\"\n >\n <mat-form-field appearance=\"outline\" class=\"flex-1\">\n <mat-label class=\"flex items-center gap-2\">\n <i class=\"fa fa-calendar text-gray-400\"></i>\n <span>Data Inicial</span>\n </mat-label>\n <input\n matInput\n (keyup.enter)=\"search()\"\n formControlName=\"initialDate\"\n [dropSpecialCharacters]=\"false\"\n mask=\"d0/M0/0000\"\n placeholder=\"DD/MM/AAAA\"\n maxlength=\"10\"\n />\n </mat-form-field>\n\n <mat-form-field appearance=\"outline\" class=\"flex-1\">\n <mat-label class=\"flex items-center gap-2\">\n <i class=\"fa fa-calendar text-gray-400\"></i>\n <span>Data Final</span>\n </mat-label>\n <input\n (keyup.enter)=\"search()\"\n matInput\n formControlName=\"finalDate\"\n [dropSpecialCharacters]=\"false\"\n mask=\"d0/M0/0000\"\n placeholder=\"DD/MM/AAAA\"\n maxlength=\"10\"\n />\n </mat-form-field>\n </div>\n </div>\n\n <!-- REMOVE FILTER BUTTON -->\n <div *ngIf=\"filtersForm.length > 1\" class=\"ml-auto flex-shrink-0\">\n <button\n (click)=\"removeFilter(i)\"\n class=\"flex h-10 w-10 items-center justify-center rounded-full transition-colors duration-300 hover:bg-red-100\"\n matTooltip=\"Remover filtro\"\n >\n <i class=\"fa fa-trash text-red-500 hover:text-red-600\"></i>\n </button>\n </div>\n </div>\n </div>\n\n <!-- PANEL FOOTER: Add Filter & Sort -->\n <div\n class=\"-mb-2 flex flex-col items-center justify-between gap-4 border-t border-gray-200 pt-4 sm:flex-row\"\n >\n <!-- Add Filter Button -->\n <div *ngIf=\"dropdownItems.length > 0\">\n <button\n (click)=\"addFilter()\"\n class=\"transform rounded-full border-2 border-blue-300 bg-blue-50 px-6 py-2 text-sm font-medium text-blue-600 transition-all duration-300 hover:-translate-y-0.5 hover:border-blue-400 hover:bg-blue-100 hover:shadow-md\"\n matTooltip=\"Adicionar novo filtro\"\n >\n <i class=\"fa fa-plus mr-2\"></i>\n Adicionar Filtro\n </button>\n </div>\n\n <!-- Sort Dropdown -->\n <div\n class=\"w-full sm:w-auto sm:min-w-[250px]\"\n *ngIf=\"sortableDropdownItems.length > 0\"\n >\n <mat-form-field appearance=\"outline\" class=\"w-full\">\n <mat-label>Ordenar por</mat-label>\n <mat-select placeholder=\"Selecione...\" [formControl]=\"selectSort\">\n <mat-option\n *ngFor=\"let item of sortableDropdownItems\"\n [value]=\"item\"\n >\n <div class=\"flex items-center gap-2\">\n <i class=\"fa fa-sort-alpha-down text-cyan-600\"></i>\n <span>{{ item.title }}</span>\n </div>\n </mat-option>\n </mat-select>\n </mat-form-field>\n </div>\n </div>\n </div>\n\n <!-- SIMPLE SEARCH (for non-paginated tables) -->\n <div\n class=\"rounded-xl border border-gray-200 bg-white p-4 shadow-lg\"\n *ngIf=\"data.pagination === false\"\n >\n <mat-form-field appearance=\"outline\" class=\"w-full\">\n <mat-label class=\"flex items-center gap-2\">\n <i class=\"fa fa-search text-blue-500\"></i>\n Buscar\n </mat-label>\n <input\n matInput\n (keyup.enter)=\"search()\"\n (keyup)=\"applyFilter(filterInput.value)\"\n placeholder=\"Digite para filtrar...\"\n #filterInput\n />\n <mat-icon matSuffix class=\"text-gray-500\">search</mat-icon>\n </mat-form-field>\n <button\n *ngIf=\"data.actionButton\"\n [ngClass]=\"\n (data.actionButton.colorClass || 'bg-blue-500') +\n ' float-right flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium text-white hover:opacity-70'\n \"\n [routerLink]=\"data.actionButton.routerLink\"\n (click)=\"\n data.actionButton.method ? data.actionButton.method($event) : null\n \"\n >\n <i *ngIf=\"data.actionButton.icon\" [class]=\"data.actionButton.icon\"></i>\n {{ data.actionButton.label }}\n </button>\n </div>\n\n <div class=\"flex flex-col\">\n <div\n class=\"mx-auto flex flex-col\"\n *ngIf=\"data.tabs && data.tabs.tabsData && data.tabs.tabsData.length > 0\"\n >\n <!-- Calcular quantos grupos de 6 tabs existem -->\n <ng-container\n *ngFor=\"\n let groupIndex of getTabGroups(data.tabs.tabsData);\n let i = index\n \"\n >\n <div class=\"mx-auto flex flex-row\">\n <ng-container\n *ngFor=\"\n let tab of getTabGroup(data.tabs.tabsData, groupIndex);\n let j = index\n \"\n >\n <button\n class=\"border-2 border-gray-300 bg-gray-200 px-4 py-2 font-medium transition hover:brightness-95\"\n [ngClass]=\"\n isTabSelected(getRealTabIndex(i, j))\n ? 'border-b-0 brightness-110'\n : ''\n \"\n (click)=\"onTableSelected(i, j)\"\n >\n {{ tab.label }}\n <span\n *ngIf=\"tab.counter !== undefined\"\n class=\"ml-2 text-xs font-bold\"\n [ngClass]=\"tab.counterClass\"\n >\n {{ tab.counter }}\n </span>\n </button>\n </ng-container>\n </div>\n </ng-container>\n </div>\n <div class=\"mat-elevation-z8 w-full overflow-x-auto rounded-xl\">\n <table\n mat-table\n [dataSource]=\"dataSource\"\n matSort\n #sort=\"matSort\"\n matSortActive=\"createdAt\"\n matSortDirection=\"desc\"\n >\n <ng-container\n *ngFor=\"let col of data.displayedColumns\"\n matColumnDef=\"{{ col.property }}\"\n >\n <ng-container *matHeaderCellDef>\n <!-- IF THE COLUMN IS NOT SORTABLE, THEN DON'T SHOW THE SORT BUTTONS -->\n <th\n *ngIf=\"!col.isSortable || data.pagination === true\"\n mat-header-cell\n [ngClass]=\"\n (data?.color?.bg ? ' ' + $any(data.color).bg : '') +\n (data?.color?.text ? ' ' + $any(data.color).text : '')\n \"\n >\n {{ col.title }}\n </th>\n <!-- IF THE COLUMN IS SORTABLE, THEN SHOW THE SORT BUTTONS -->\n <th\n *ngIf=\"col.isSortable && data.pagination === false\"\n mat-header-cell\n mat-sort-header\n [ngClass]=\"\n (data?.color?.bg ? ' ' + $any(data.color).bg : '') +\n (data?.color?.text ? ' ' + $any(data.color).text : '')\n \"\n >\n {{ col.title }}\n </th>\n <td\n mat-cell\n *matCellDef=\"let row\"\n (click)=\"col.method ? col.method(row) : null\"\n (mouseenter)=\"onCellMouseEnter($event, row, col)\"\n (mouseleave)=\"onCellMouseLeave()\"\n (mousemove)=\"onCellMouseMove($event)\"\n >\n <!-- CHECK IF THE COLUMN MUST BE DISPLAYED -->\n <span *ngIf=\"!col.image && !col.iconClass && !col.method\">\n <ng-container>\n <span\n *ngIf=\"\n col.charLimit &&\n row[col.property] &&\n row[col.property].length > col.charLimit;\n else withinLimit\n \"\n >\n <a\n *ngIf=\"col.hasLink === true\"\n [href]=\"row[col.property]\"\n target=\"_blank\"\n >\n {{ getDisplayValue(col, row) }}\n </a>\n <a\n *ngIf=\"col.hasLink && isString(col.hasLink)\"\n [href]=\"col.hasLink\"\n target=\"_blank\"\n >\n {{ getDisplayValue(col, row) }}\n </a>\n <span\n *ngIf=\"col.hasLink !== true && !isString(col.hasLink)\"\n >\n {{ getDisplayValue(col, row) }}\n </span>\n </span>\n </ng-container>\n <ng-template #withinLimit>\n <a\n *ngIf=\"col.hasLink === true\"\n [href]=\"row[col.property]\"\n target=\"_blank\"\n >\n {{ getDisplayValue(col, row, true) }}\n </a>\n <a\n *ngIf=\"col.hasLink && isString(col.hasLink)\"\n [href]=\"col.hasLink\"\n target=\"_blank\"\n >\n {{ getDisplayValue(col, row, true) }}\n </a>\n <span\n *ngIf=\"col.hasLink !== true && !isString(col.hasLink)\"\n >\n {{ getDisplayValue(col, row, true) }}\n </span>\n </ng-template>\n </span>\n <!------------------- IMAGE ------------------>\n <img\n *ngIf=\"\n col.image && col.image.path && !col.iconClass && !col.method\n \"\n [src]=\"col.image.path + '/' + row[col.property]\"\n [ngClass]=\"col.image.class\"\n alt=\"Imagem\"\n />\n <img\n *ngIf=\"\n col.image && col.image.url && !col.iconClass && !col.method\n \"\n [src]=\"row[col.property]\"\n [ngClass]=\"col.image.class\"\n alt=\"Imagem\"\n />\n <ng-container *ngIf=\"col.iconClass\">\n <button\n *ngFor=\"let iconClass of col.iconClass\"\n (click)=\"\n iconClass.buttonMethod\n ? iconClass.buttonMethod(row, $event)\n : $event.stopPropagation()\n \"\n >\n <span\n [ngClass]=\"iconClass.class\"\n *ngIf=\"\n iconClass.condition === undefined ||\n (iconClass.condition !== undefined &&\n $any(iconClass.condition)(row))\n \"\n >{{ iconClass.text }}</span\n >\n </button>\n </ng-container>\n </td>\n </ng-container>\n </ng-container>\n\n <tr mat-header-row *matHeaderRowDef=\"columnProperties\"></tr>\n <tr\n [ngClass]=\"{\n 'example-element-row': data.isNotClickable === true,\n 'example-element-row cursor-pointer': !data.isNotClickable\n }\"\n mat-row\n *matRowDef=\"let row; columns: columnProperties\"\n (click)=\"goToDetails(row)\"\n ></tr>\n\n <!-- ROW SHOWN WHEN THERE IS NO MATCHING DATA. -->\n <tr class=\"mat-row\" *matNoDataRow>\n <td *ngIf=\"!isLoading\" class=\"mat-cell p-4\" colspan=\"4\">\n Nenhum resultado encontrado para a busca\n </td>\n </tr>\n </table>\n\n <div class=\"flex justify-center\" *ngIf=\"isLoading\">\n <mat-spinner></mat-spinner>\n </div>\n\n <div class=\"paginator-container\">\n <mat-paginator\n #paginator\n [pageSizeOptions]=\"[25, 50, 100]\"\n [pageSize]=\"pageSize\"\n [length]=\"totalItems\"\n showFirstLastButtons\n aria-label=\"Select page of periodic elements\"\n (page)=\"onPageChange($event)\"\n [ngClass]=\"{\n 'hide-length':\n ['filter', 'filterByDate', 'equals'].includes(\n this.currentArrange\n ) || this.data.filterFn,\n 'hide-next-button': !hasNextPage && data.pagination === true,\n 'hide-last-button':\n (!hasNextPage && data.pagination === true) || this.data.filterFn\n }\"\n >\n </mat-paginator>\n <div\n *ngIf=\"\n !isLoading &&\n dataSource?.data &&\n dataSource.data.length > 0 &&\n data?.filterFn\n \"\n class=\"page-number-display\"\n >\n {{ currentPageNumber }}\n </div>\n </div>\n </div>\n </div>\n </div>\n\n <!-- TOOLTIP PERSONALIZADO -->\n <div\n *ngIf=\"showTooltip\"\n class=\"fixed z-50 max-w-md break-words rounded-lg bg-gray-800 px-3 py-2 text-sm text-white shadow-lg\"\n [style.left.px]=\"tooltipPosition.x\"\n [style.top.px]=\"tooltipPosition.y\"\n [style.pointer-events]=\"'none'\"\n >\n {{ tooltipContent }}\n </div>\n</div>\n", styles: ["::ng-deep .hide-length .mat-mdc-paginator-range-label{display:none}::ng-deep .hide-next-button .mat-mdc-tooltip-trigger.mat-mdc-paginator-navigation-next.mdc-icon-button.mat-mdc-icon-button.mat-unthemed.mat-mdc-button-base{visibility:hidden}::ng-deep .hide-next-button .mat-mdc-tooltip-trigger.mat-mdc-paginator-navigation-last.mdc-icon-button.mat-mdc-icon-button.mat-unthemed.mat-mdc-button-base.ng-star-inserted{visibility:hidden}::ng-deep .mat-mdc-text-field-wrapper.mdc-text-field.ng-tns-c162-1.mdc-text-field--filled{width:25dvw}::ng-deep .custom-filter .mat-mdc-text-field-wrapper{width:20dvw;max-width:300px}\n"] }]
1921
- }], ctorParameters: function () { return [{ type: i1$1.Router }, { type: TableService }, { type: i1.AngularFirestore }]; }, propDecorators: { data: [{
1922
- type: Input
1923
- }], downloadTable: [{
1924
- type: Input
1925
- }], paginator: [{
1926
- type: ViewChild,
1927
- args: [MatPaginator]
1928
- }], sort: [{
1929
- type: ViewChild,
1930
- args: [MatSort]
1152
+ class TableComponent {
1153
+ // CONSTRUCTOR
1154
+ constructor(router, tableService, firestore) {
1155
+ this.router = router;
1156
+ this.tableService = tableService;
1157
+ this.firestore = firestore;
1158
+ this.arrange = null;
1159
+ this.currentPageNumber = 1;
1160
+ this.currentClientPageIndex = 0;
1161
+ this.items = [];
1162
+ this.isLoading = false;
1163
+ this.lastDoc = null;
1164
+ this.firstDoc = null;
1165
+ this.sortBy = {
1166
+ field: 'createdAt',
1167
+ order: 'desc',
1168
+ };
1169
+ this.columnProperties = [];
1170
+ this.selectSort = new FormControl('');
1171
+ this.currentArrange = '';
1172
+ this.hasNextPage = false;
1173
+ this.dropdownItems = [];
1174
+ this.sortableDropdownItems = [];
1175
+ this.pageSize = 25;
1176
+ this.totalItems = 0;
1177
+ this.filterValue = null;
1178
+ this.hasFilterableColumn = false;
1179
+ this.hasSortableColumn = false;
1180
+ this.filterSubject = new Subject();
1181
+ this.debounceTimeMs = 500;
1182
+ this.selectedTab = 0;
1183
+ // Propriedades para controle do tooltip
1184
+ this.hoveredCell = null;
1185
+ this.showTooltip = false;
1186
+ this.tooltipContent = '';
1187
+ this.tooltipPosition = { x: 0, y: 0 };
1188
+ this.filtersForm = new FormArray([this.createFilterGroup()]);
1189
+ }
1190
+ createFilterGroup() {
1191
+ return new FormGroup({
1192
+ selectFilter: new FormControl(''),
1193
+ typeFilter: new FormControl(''),
1194
+ selectItem: new FormControl(''),
1195
+ initialDate: new FormControl('', this.tableService.dateFormatValidator()),
1196
+ finalDate: new FormControl('', this.tableService.dateFormatValidator()),
1197
+ });
1198
+ }
1199
+ addFilter(filterData) {
1200
+ const newFilterGroup = this.createFilterGroup();
1201
+ if (filterData) {
1202
+ if (filterData.selectFilter) {
1203
+ newFilterGroup.get('selectFilter')?.setValue(filterData.selectFilter);
1204
+ }
1205
+ if (filterData.typeFilter) {
1206
+ newFilterGroup.get('typeFilter')?.setValue(filterData.typeFilter);
1207
+ }
1208
+ if (filterData.selectItem) {
1209
+ newFilterGroup.get('selectItem')?.setValue(filterData.selectItem);
1210
+ }
1211
+ if (filterData.initialDate) {
1212
+ newFilterGroup.get('initialDate')?.setValue(filterData.initialDate);
1213
+ }
1214
+ if (filterData.finalDate) {
1215
+ newFilterGroup.get('finalDate')?.setValue(filterData.finalDate);
1216
+ }
1217
+ }
1218
+ this.filtersForm.push(newFilterGroup);
1219
+ }
1220
+ onSelectFilterChange() {
1221
+ const lastIndex = this.filtersForm.length - 1;
1222
+ const lastFilter = this.filtersForm.at(lastIndex);
1223
+ if (lastFilter.get('selectFilter')?.value) {
1224
+ this.addFilter();
1225
+ }
1226
+ }
1227
+ removeFilter(index) {
1228
+ this.filtersForm.removeAt(index);
1229
+ if (this.filtersForm.length === 0) {
1230
+ this.addFilter();
1231
+ }
1232
+ }
1233
+ removeAllFilters() {
1234
+ this.filtersForm.clear();
1235
+ this.addFilter();
1236
+ this.resetFilter();
1237
+ }
1238
+ // METHODS
1239
+ async ngOnInit() {
1240
+ if (!this.data.color)
1241
+ this.data.color = { bg: 'bg-primary', text: 'text-black' };
1242
+ this.columnProperties = this.data.displayedColumns.map((column) => {
1243
+ return column.property;
1244
+ });
1245
+ if (this.data.actionButton && !this.data.actionButton.condition) {
1246
+ this.data.actionButton.condition = (_row) => true;
1247
+ }
1248
+ this.data.displayedColumns.forEach((col) => {
1249
+ if (col.isFilterable) {
1250
+ if (this.hasFilterableColumn === false)
1251
+ this.hasFilterableColumn = true;
1252
+ this.dropdownItems.push({
1253
+ ...col,
1254
+ arrange: 'filter',
1255
+ title: col.title,
1256
+ });
1257
+ }
1258
+ if (col.isSortable) {
1259
+ if (this.hasSortableColumn === false)
1260
+ this.hasSortableColumn = true;
1261
+ this.sortableDropdownItems.push({
1262
+ ...col,
1263
+ arrange: 'ascending',
1264
+ title: col.title + ': crescente',
1265
+ });
1266
+ this.sortableDropdownItems.push({
1267
+ ...col,
1268
+ arrange: 'descending',
1269
+ title: col.title + ': decrescente',
1270
+ });
1271
+ }
1272
+ if (col.isFilterableByDate) {
1273
+ this.dropdownItems.push({
1274
+ ...col,
1275
+ arrange: 'filterByDate',
1276
+ title: col.title + ': filtro por data',
1277
+ });
1278
+ }
1279
+ });
1280
+ if (this.data.filterableOptions &&
1281
+ Array.isArray(this.data.filterableOptions) &&
1282
+ this.data.filterableOptions.length > 0) {
1283
+ this.data.filterableOptions.forEach((option) => this.dropdownItems.push({ ...option, arrange: 'equals' }));
1284
+ }
1285
+ // Sem paginação
1286
+ if (this.data.pagination === false) {
1287
+ await this.loadItems();
1288
+ }
1289
+ // Com paginação
1290
+ if (this.data.pagination === true) {
1291
+ if (this.data.sortBy)
1292
+ this.sortBy = {
1293
+ field: this.data.sortBy.field,
1294
+ order: this.data.sortBy.order,
1295
+ };
1296
+ this.filterSubject
1297
+ .pipe(debounceTime(this.debounceTimeMs))
1298
+ .subscribe(() => {
1299
+ this.loadItemsPaginated('reload', true);
1300
+ });
1301
+ this.isLoading = true;
1302
+ await this.loadItemsPaginated('reload', true);
1303
+ this.sort.active = 'createdAt';
1304
+ this.sort.direction = 'desc';
1305
+ this.dataSource.paginator = this.paginator;
1306
+ this.dataSource.sort = this.sort;
1307
+ this.totalItems = 0;
1308
+ if (this.data.totalRef) {
1309
+ for (const totalRef of this.data.totalRef) {
1310
+ const totalRefDoc = await totalRef.ref.get();
1311
+ const docData = totalRefDoc.data();
1312
+ if (docData && docData[totalRef.field])
1313
+ this.totalItems = (this.totalItems +
1314
+ docData[totalRef.field]);
1315
+ }
1316
+ }
1317
+ this.isLoading = false;
1318
+ }
1319
+ }
1320
+ getDisplayValue(col, row, withinLimit = false) {
1321
+ let value;
1322
+ if (col.calculateValue) {
1323
+ value = col.calculateValue(row);
1324
+ }
1325
+ else {
1326
+ value = this.getNestedValue(row, col.property);
1327
+ }
1328
+ if (Array.isArray(value) && col.arrayField) {
1329
+ value = this.formatArrayValue(value, col.arrayField);
1330
+ }
1331
+ if (col.queryLength && row[col.property]) {
1332
+ value = row[col.property];
1333
+ }
1334
+ value = col.pipe ? col.pipe.transform(value) : value;
1335
+ if (value === null || value === undefined) {
1336
+ value = '';
1337
+ }
1338
+ else {
1339
+ value = String(value);
1340
+ }
1341
+ if (typeof value !== 'string') {
1342
+ value = '';
1343
+ }
1344
+ if (withinLimit || !col.charLimit) {
1345
+ return value;
1346
+ }
1347
+ return value.substring(0, col.charLimit) + '...';
1348
+ }
1349
+ getNestedValue(obj, path) {
1350
+ if (!path)
1351
+ return undefined;
1352
+ const properties = path.split('.');
1353
+ return properties.reduce((acc, currentPart) => acc && acc[currentPart], obj);
1354
+ }
1355
+ formatArrayValue(array, field) {
1356
+ if (!Array.isArray(array) || array.length === 0) {
1357
+ return '';
1358
+ }
1359
+ const values = array
1360
+ .map((item) => {
1361
+ if (typeof item === 'object' && item !== null) {
1362
+ return item[field] || '';
1363
+ }
1364
+ return String(item);
1365
+ })
1366
+ .filter((value) => value !== '' && value !== null && value !== undefined);
1367
+ return values.join(', ');
1368
+ }
1369
+ // Métodos sem paginação
1370
+ async loadItems() {
1371
+ this.items = await this.tableService.getItems(this.data.collectionRef);
1372
+ if (this.data.conditions) {
1373
+ this.filterItems();
1374
+ }
1375
+ await this.loadRelations();
1376
+ await this.loadQueryLengths();
1377
+ this.totalItems = this.items.length;
1378
+ // Aplicar filtros client-side se existirem
1379
+ let itemsToDisplay = [...this.items];
1380
+ itemsToDisplay = this.applyClientSideFilters(itemsToDisplay);
1381
+ this.dataSource = new MatTableDataSource(itemsToDisplay);
1382
+ this.dataSource.paginator = this.paginator;
1383
+ this.dataSource.sort = this.sort;
1384
+ if (this.data.sortBy) {
1385
+ this.dataSource.sort.active = this.data.sortBy.field;
1386
+ this.dataSource.sort.direction = this.data.sortBy.order;
1387
+ this.dataSource.sort.sortChange.emit();
1388
+ }
1389
+ this.dataSource.filterPredicate = (data, filter) => {
1390
+ return this.data.displayedColumns.some((col) => {
1391
+ if (col.filterPredicates) {
1392
+ return col.filterPredicates.some((predicate) => {
1393
+ const propertyValue = data[col.property];
1394
+ if (!propertyValue || typeof propertyValue !== 'object') {
1395
+ return false;
1396
+ }
1397
+ const predicateValue = propertyValue[predicate];
1398
+ if (predicateValue === null || predicateValue === undefined) {
1399
+ return false;
1400
+ }
1401
+ return String(predicateValue)
1402
+ .trim()
1403
+ .toLocaleLowerCase()
1404
+ .includes(filter);
1405
+ });
1406
+ }
1407
+ if (col.property && col.isFilterable) {
1408
+ const propertyValue = data[col.property];
1409
+ if (propertyValue === null || propertyValue === undefined) {
1410
+ return false;
1411
+ }
1412
+ return String(propertyValue)
1413
+ .trim()
1414
+ .toLocaleLowerCase()
1415
+ .includes(filter);
1416
+ }
1417
+ return false;
1418
+ });
1419
+ };
1420
+ this.filterPredicate = this.dataSource.filterPredicate;
1421
+ }
1422
+ // Aplicar filtros client-side (filtros por data)
1423
+ applyClientSideFilters(items) {
1424
+ let filteredItems = [...items];
1425
+ // Processar filtros do filtersForm
1426
+ this.filtersForm.controls.forEach((control) => {
1427
+ const group = control;
1428
+ const selectedFilter = group.get('selectFilter')?.value;
1429
+ if (!selectedFilter)
1430
+ return;
1431
+ const arrange = selectedFilter.arrange;
1432
+ if (arrange === 'filterByDate') {
1433
+ const initial = group.get('initialDate')?.value;
1434
+ const final = group.get('finalDate')?.value;
1435
+ // Só aplicar filtro se ambas as datas estiverem preenchidas
1436
+ if (initial && final && initial.trim() && final.trim()) {
1437
+ try {
1438
+ // Validar formato da data (DD/MM/AAAA)
1439
+ const datePattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
1440
+ if (!datePattern.test(initial) || !datePattern.test(final)) {
1441
+ return; // Ignorar se formato inválido
1442
+ }
1443
+ const [dayI, monthI, yearI] = initial.split('/');
1444
+ const initialDate = new Date(`${monthI}/${dayI}/${yearI}`);
1445
+ const [dayF, monthF, yearF] = final.split('/');
1446
+ const finalDate = new Date(`${monthF}/${dayF}/${yearF}`);
1447
+ finalDate.setHours(23, 59, 59);
1448
+ // Validar se as datas são válidas
1449
+ if (isNaN(initialDate.getTime()) || isNaN(finalDate.getTime())) {
1450
+ return; // Ignorar se datas inválidas
1451
+ }
1452
+ // Usar o campo da coluna ou o sortBy.field como padrão
1453
+ const dateField = selectedFilter.property || this.sortBy.field;
1454
+ filteredItems = filteredItems.filter((item) => {
1455
+ try {
1456
+ const fieldValue = item[dateField];
1457
+ if (!fieldValue) {
1458
+ return false;
1459
+ }
1460
+ let itemDate;
1461
+ if (typeof fieldValue.toDate === 'function') {
1462
+ itemDate = fieldValue.toDate();
1463
+ }
1464
+ else if (fieldValue instanceof Date) {
1465
+ itemDate = fieldValue;
1466
+ }
1467
+ else if (typeof fieldValue === 'string') {
1468
+ itemDate = new Date(fieldValue);
1469
+ if (isNaN(itemDate.getTime())) {
1470
+ return false;
1471
+ }
1472
+ }
1473
+ else if (typeof fieldValue === 'number') {
1474
+ itemDate = new Date(fieldValue);
1475
+ }
1476
+ else {
1477
+ return false;
1478
+ }
1479
+ return itemDate >= initialDate && itemDate <= finalDate;
1480
+ }
1481
+ catch (error) {
1482
+ console.warn('Erro ao processar filtro de data para o item:', item.id, error);
1483
+ return false;
1484
+ }
1485
+ });
1486
+ }
1487
+ catch (error) {
1488
+ console.warn('Erro ao processar datas do filtro:', error);
1489
+ }
1490
+ }
1491
+ // Se as datas não estiverem preenchidas, não aplicar filtro (retornar todos os itens)
1492
+ }
1493
+ });
1494
+ return filteredItems;
1495
+ }
1496
+ // Handler para mudanças de data no filtro
1497
+ onDateFilterChange() {
1498
+ if (this.data.pagination === false) {
1499
+ // Aplicar filtros (ou remover se campos estiverem vazios)
1500
+ this.applyFiltersToDataSource();
1501
+ }
1502
+ }
1503
+ // Aplicar filtros ao dataSource quando não há paginação
1504
+ applyFiltersToDataSource() {
1505
+ if (!this.dataSource)
1506
+ return;
1507
+ let filteredItems = this.applyClientSideFilters([...this.items]);
1508
+ this.dataSource.data = filteredItems;
1509
+ this.totalItems = filteredItems.length;
1510
+ }
1511
+ // Métodos com paginação
1512
+ async loadItemsPaginated(navigation = 'reload', reset = false) {
1513
+ if (reset && ['forward', 'reload'].includes(navigation)) {
1514
+ this.lastDoc = null;
1515
+ this.currentClientPageIndex = 0;
1516
+ }
1517
+ if (reset && ['backward', 'reload'].includes(navigation)) {
1518
+ this.firstDoc = null;
1519
+ this.currentClientPageIndex = 0;
1520
+ }
1521
+ const activeFilters = this.filtersForm.controls
1522
+ .flatMap((control) => {
1523
+ const group = control;
1524
+ const selectedFilter = group.get('selectFilter')?.value;
1525
+ if (!selectedFilter)
1526
+ return [];
1527
+ const arrange = selectedFilter.arrange;
1528
+ if (arrange === 'filter') {
1529
+ const filterValue = group.get('typeFilter')?.value;
1530
+ if (!filterValue)
1531
+ return [];
1532
+ return {
1533
+ arrange,
1534
+ filter: {
1535
+ property: selectedFilter.property,
1536
+ filtering: filterValue,
1537
+ },
1538
+ dateFilter: undefined,
1539
+ };
1540
+ }
1541
+ if (arrange === 'filterByDate') {
1542
+ const initial = group.get('initialDate')?.value;
1543
+ const final = group.get('finalDate')?.value;
1544
+ if (initial && final) {
1545
+ const [dayI, monthI, yearI] = initial.split('/');
1546
+ const initialDate = new Date(`${monthI}/${dayI}/${yearI}`);
1547
+ const [dayF, monthF, yearF] = final.split('/');
1548
+ const finalDate = new Date(`${monthF}/${dayF}/${yearF}`);
1549
+ finalDate.setHours(23, 59, 59);
1550
+ return {
1551
+ arrange,
1552
+ filter: undefined,
1553
+ dateFilter: {
1554
+ initial: initialDate,
1555
+ final: finalDate,
1556
+ },
1557
+ };
1558
+ }
1559
+ return [];
1560
+ }
1561
+ if (selectedFilter.hasOwnProperty('items') && arrange === 'equals') {
1562
+ const selectedItems = group.get('selectItem')?.value;
1563
+ if (Array.isArray(selectedItems) && selectedItems.length > 0) {
1564
+ return selectedItems.map((item) => ({
1565
+ arrange,
1566
+ filter: {
1567
+ property: item.property,
1568
+ filtering: item.value,
1569
+ },
1570
+ dateFilter: undefined,
1571
+ }));
1572
+ }
1573
+ }
1574
+ return [];
1575
+ })
1576
+ .filter((f) => f && (f.filter?.filtering !== undefined || f.dateFilter));
1577
+ this.arrange = {
1578
+ filters: activeFilters,
1579
+ sortBy: this.sortBy,
1580
+ };
1581
+ const paginated = {
1582
+ batchSize: this.pageSize,
1583
+ collection: this.data.collection,
1584
+ doc: { lastDoc: this.lastDoc, firstDoc: this.firstDoc },
1585
+ navigation,
1586
+ arrange: this.arrange,
1587
+ conditions: this.data.conditions,
1588
+ size: this.totalItems,
1589
+ filterFn: this.data.filterFn,
1590
+ clientPageIndex: this.currentClientPageIndex,
1591
+ };
1592
+ const result = await this.tableService.getPaginated(paginated);
1593
+ this.items = result.items;
1594
+ await this.loadRelations();
1595
+ await this.loadQueryLengths();
1596
+ this.lastDoc = result.lastDoc;
1597
+ this.firstDoc = result.firstDoc;
1598
+ // Atualizar currentClientPageIndex se retornado pelo fallback
1599
+ if (result.currentClientPageIndex !== undefined) {
1600
+ this.currentClientPageIndex = result.currentClientPageIndex;
1601
+ }
1602
+ let sum = 0;
1603
+ if (this.data.totalRef) {
1604
+ for (const totalRef of this.data.totalRef) {
1605
+ const totalRefDoc = await totalRef.ref.get();
1606
+ const docData = totalRefDoc.data();
1607
+ if (docData || result.filterLength) {
1608
+ sum =
1609
+ result.filterLength ??
1610
+ (sum + (docData ? docData[totalRef.field] : 0));
1611
+ }
1612
+ }
1613
+ this.totalItems = sum;
1614
+ }
1615
+ this.hasNextPage = result.hasNextPage;
1616
+ this.dataSource = new MatTableDataSource(this.items);
1617
+ this.filterPredicate = this.dataSource.filterPredicate;
1618
+ }
1619
+ async onPageChange(event) {
1620
+ if (this.data.pagination === true && event) {
1621
+ this.isLoading = true;
1622
+ const previousPageIndex = event.previousPageIndex ?? 0;
1623
+ const pageIndex = event.pageIndex;
1624
+ const currentComponentPageSize = this.pageSize;
1625
+ const eventPageSize = event.pageSize;
1626
+ const totalItems = this.totalItems;
1627
+ let navigationDirection;
1628
+ let resetDocs = false;
1629
+ let originalPageSize = null;
1630
+ const lastPageIndex = Math.max(0, Math.ceil(totalItems / eventPageSize) - 1);
1631
+ // Atualizar currentClientPageIndex sempre para o fallback
1632
+ this.currentClientPageIndex = pageIndex;
1633
+ if (previousPageIndex !== undefined && pageIndex > previousPageIndex) {
1634
+ this.currentPageNumber++;
1635
+ }
1636
+ else if (previousPageIndex !== undefined &&
1637
+ pageIndex < previousPageIndex) {
1638
+ this.currentPageNumber = Math.max(1, this.currentPageNumber - 1);
1639
+ }
1640
+ if (eventPageSize !== currentComponentPageSize) {
1641
+ console.log('Alterou a quantidade de elementos exibidos por página');
1642
+ this.pageSize = eventPageSize;
1643
+ navigationDirection = 'forward';
1644
+ resetDocs = true;
1645
+ this.currentClientPageIndex = 0;
1646
+ }
1647
+ else if (pageIndex === 0 &&
1648
+ previousPageIndex !== undefined &&
1649
+ pageIndex < previousPageIndex) {
1650
+ console.log('Pulou para a primeira página');
1651
+ navigationDirection = 'forward';
1652
+ this.currentPageNumber = 1;
1653
+ this.currentClientPageIndex = 0;
1654
+ resetDocs = true;
1655
+ }
1656
+ else if (pageIndex === lastPageIndex &&
1657
+ previousPageIndex !== undefined &&
1658
+ pageIndex > previousPageIndex &&
1659
+ pageIndex - previousPageIndex > 1) {
1660
+ console.log('Pulou para a ultima página');
1661
+ navigationDirection = 'backward';
1662
+ resetDocs = true;
1663
+ const itemsExpectedInLastPage = totalItems - lastPageIndex * eventPageSize;
1664
+ if (itemsExpectedInLastPage > 0 &&
1665
+ itemsExpectedInLastPage < eventPageSize) {
1666
+ originalPageSize = this.pageSize;
1667
+ this.pageSize = itemsExpectedInLastPage;
1668
+ }
1669
+ }
1670
+ else if (previousPageIndex !== undefined &&
1671
+ pageIndex > previousPageIndex) {
1672
+ console.log('Procedendo');
1673
+ navigationDirection = 'forward';
1674
+ resetDocs = false;
1675
+ }
1676
+ else if (previousPageIndex !== undefined &&
1677
+ pageIndex < previousPageIndex) {
1678
+ console.log('Retrocedendo.');
1679
+ navigationDirection = 'backward';
1680
+ resetDocs = false;
1681
+ }
1682
+ else if (previousPageIndex !== undefined &&
1683
+ pageIndex === previousPageIndex) {
1684
+ console.log('Recarregando.');
1685
+ navigationDirection = 'reload';
1686
+ resetDocs = false;
1687
+ }
1688
+ else if (previousPageIndex === undefined && pageIndex === 0) {
1689
+ console.log('Evento inicial do paginador para pág 0. ngOnInit carregou.');
1690
+ this.isLoading = false;
1691
+ if (event)
1692
+ this.pageEvent = event;
1693
+ return;
1694
+ }
1695
+ else {
1696
+ console.warn('INESPERADO! Condição de navegação não tratada:', event);
1697
+ this.isLoading = false;
1698
+ if (event)
1699
+ this.pageEvent = event;
1700
+ return;
1701
+ }
1702
+ if (navigationDirection) {
1703
+ try {
1704
+ await this.loadItemsPaginated(navigationDirection, resetDocs);
1705
+ }
1706
+ catch (error) {
1707
+ console.error('Erro ao carregar itens paginados:', error);
1708
+ }
1709
+ finally {
1710
+ if (originalPageSize !== null) {
1711
+ this.pageSize = originalPageSize;
1712
+ }
1713
+ }
1714
+ }
1715
+ if (event)
1716
+ this.pageEvent = event;
1717
+ this.isLoading = false;
1718
+ }
1719
+ }
1720
+ // Outros métodos
1721
+ applyFilter(value) {
1722
+ // Sem paginação
1723
+ if (this.data.pagination === false) {
1724
+ this.dataSource.filter = String(value).trim().toLowerCase();
1725
+ }
1726
+ // Com paginação
1727
+ if (this.data.pagination === true) {
1728
+ this.filterValue = value;
1729
+ this.filterSubject.next(this.filterValue);
1730
+ }
1731
+ }
1732
+ goToDetails(row) {
1733
+ if (this.data.isNotClickable) {
1734
+ return;
1735
+ }
1736
+ const urlPath = this.data.url || this.data.name;
1737
+ const url = this.router.serializeUrl(this.router.createUrlTree([`/${urlPath}`, row.id]));
1738
+ window.open(url, '_blank');
1739
+ }
1740
+ async getRelation(params) {
1741
+ try {
1742
+ let snapshot;
1743
+ if (params.id !== '' &&
1744
+ params.id !== undefined &&
1745
+ params.collection !== undefined &&
1746
+ params.collection !== '') {
1747
+ snapshot = await firstValueFrom(this.firestore.collection(params.collection).doc(params.id).get());
1748
+ }
1749
+ if (snapshot && snapshot.exists) {
1750
+ const data = snapshot.data();
1751
+ return data?.[params.newProperty] ?? '';
1752
+ }
1753
+ return '';
1754
+ }
1755
+ catch (e) {
1756
+ console.log(e);
1757
+ return '';
1758
+ }
1759
+ }
1760
+ async loadRelations() {
1761
+ const relationPromises = this.data.displayedColumns
1762
+ .filter((col) => col.relation)
1763
+ .flatMap((col) => this.items.map(async (item) => {
1764
+ if (col.relation) {
1765
+ item[col.property] = await this.getRelation({
1766
+ id: item[col.relation.property],
1767
+ collection: col.relation.collection,
1768
+ newProperty: col.relation.newProperty,
1769
+ });
1770
+ }
1771
+ }));
1772
+ await Promise.all(relationPromises);
1773
+ }
1774
+ async getQueryLength(params) {
1775
+ const snapshot = await this.firestore
1776
+ .collection(params.relation.collection)
1777
+ .ref.where(params.relation.property, params.relation.operator, params.item[params.relation.value])
1778
+ .get();
1779
+ return snapshot.size;
1780
+ }
1781
+ async loadQueryLengths() {
1782
+ const lengthPromises = this.data.displayedColumns
1783
+ .filter((col) => col.queryLength)
1784
+ .flatMap((col) => this.items.map(async (item) => {
1785
+ if (col.queryLength) {
1786
+ item[col.property] = await this.getQueryLength({
1787
+ item: item,
1788
+ relation: col.queryLength,
1789
+ });
1790
+ }
1791
+ }));
1792
+ await Promise.all(lengthPromises);
1793
+ }
1794
+ filterItems() {
1795
+ if (this.data.conditions) {
1796
+ this.data.conditions.forEach((cond) => {
1797
+ this.items = this.items.filter((item) => {
1798
+ const operatorFunction = this.tableService.operators[cond.operator];
1799
+ if (operatorFunction) {
1800
+ return operatorFunction(item[cond.firestoreProperty], cond.dashProperty);
1801
+ }
1802
+ return false;
1803
+ });
1804
+ });
1805
+ }
1806
+ }
1807
+ // Filtro de data
1808
+ async search() {
1809
+ if (this.selectSort.value) {
1810
+ if (this.selectSort.value.arrange === 'ascending') {
1811
+ this.sortBy = {
1812
+ field: this.selectSort.value.property,
1813
+ order: 'asc',
1814
+ };
1815
+ }
1816
+ if (this.selectSort.value.arrange === 'descending') {
1817
+ this.sortBy = {
1818
+ field: this.selectSort.value.property,
1819
+ order: 'desc',
1820
+ };
1821
+ }
1822
+ }
1823
+ // Sem paginação: aplicar filtros client-side
1824
+ if (this.data.pagination === false) {
1825
+ this.applyFiltersToDataSource();
1826
+ this.currentArrange =
1827
+ this.filtersForm.length > 0
1828
+ ? this.filtersForm.at(0).get('selectFilter')?.value?.arrange ?? ''
1829
+ : '';
1830
+ }
1831
+ else {
1832
+ // Com paginação: comportamento original
1833
+ await this.loadItemsPaginated('reload', true);
1834
+ this.currentArrange =
1835
+ this.filtersForm.length > 0
1836
+ ? this.filtersForm.at(0).get('selectFilter')?.value?.arrange ?? ''
1837
+ : '';
1838
+ this.paginator.firstPage();
1839
+ }
1840
+ }
1841
+ async resetFilter() {
1842
+ this.dataSource.filter = '';
1843
+ if (this.filterPredicate) {
1844
+ this.dataSource.filterPredicate = this.filterPredicate;
1845
+ }
1846
+ this.filtersForm.clear();
1847
+ this.addFilter();
1848
+ this.selectSort.patchValue('');
1849
+ this.sortBy = {
1850
+ order: this.data.sortBy ? this.data.sortBy.order : 'desc',
1851
+ field: this.data.sortBy ? this.data.sortBy.field : 'createdAt',
1852
+ };
1853
+ // Sem paginação: recarregar itens originais
1854
+ if (this.data.pagination === false) {
1855
+ this.dataSource.data = [...this.items];
1856
+ this.totalItems = this.items.length;
1857
+ this.currentArrange = '';
1858
+ }
1859
+ else {
1860
+ // Com paginação: comportamento original
1861
+ await this.loadItemsPaginated('reload', true);
1862
+ this.currentArrange = '';
1863
+ this.paginator.firstPage();
1864
+ }
1865
+ }
1866
+ // Método público para recarregar a tabela
1867
+ async reloadTable() {
1868
+ if (this.data.pagination) {
1869
+ await this.loadItemsPaginated('reload', true);
1870
+ this.paginator.firstPage();
1871
+ }
1872
+ else {
1873
+ await this.loadItems();
1874
+ }
1875
+ }
1876
+ updateDisplayedColumns() {
1877
+ if (this.dataSource) {
1878
+ this.dataSource = new MatTableDataSource([]);
1879
+ }
1880
+ this.columnProperties = this.data.displayedColumns.map((column) => {
1881
+ return column.property;
1882
+ });
1883
+ this.dropdownItems = [];
1884
+ this.sortableDropdownItems = [];
1885
+ this.data.displayedColumns.forEach((col) => {
1886
+ if (col.isFilterable) {
1887
+ this.dropdownItems.push({
1888
+ ...col,
1889
+ arrange: 'filter',
1890
+ title: col.title,
1891
+ });
1892
+ }
1893
+ if (col.isSortable) {
1894
+ this.sortableDropdownItems.push({
1895
+ ...col,
1896
+ arrange: 'ascending',
1897
+ title: col.title + ': crescente',
1898
+ });
1899
+ this.sortableDropdownItems.push({
1900
+ ...col,
1901
+ arrange: 'descending',
1902
+ title: col.title + ': decrescente',
1903
+ });
1904
+ }
1905
+ if (col.isFilterableByDate) {
1906
+ this.dropdownItems.push({
1907
+ ...col,
1908
+ arrange: 'filterByDate',
1909
+ title: col.title + ': filtro por data',
1910
+ });
1911
+ }
1912
+ });
1913
+ if (this.data.filterableOptions &&
1914
+ Array.isArray(this.data.filterableOptions)) {
1915
+ this.data.filterableOptions.forEach((option) => this.dropdownItems.push({ ...option, arrange: 'equals' }));
1916
+ }
1917
+ }
1918
+ isString(value) {
1919
+ return typeof value === 'string';
1920
+ }
1921
+ // Métodos para controle do tooltip
1922
+ onCellMouseEnter(event, row, col) {
1923
+ // mostrar tooltip se a coluna tiver charLimit definido
1924
+ if (!col.charLimit) {
1925
+ return;
1926
+ }
1927
+ const fullValue = this.getDisplayValue(col, row, true);
1928
+ // mostrar tooltip se o valor completo for maior que o limite
1929
+ if (fullValue.length <= col.charLimit) {
1930
+ return;
1931
+ }
1932
+ this.hoveredCell = { row, col };
1933
+ this.tooltipContent = fullValue;
1934
+ // Definir posição do tooltip
1935
+ this.tooltipPosition = {
1936
+ x: event.clientX + 10,
1937
+ y: event.clientY - 10,
1938
+ };
1939
+ // Timeout para mostrar o tooltip
1940
+ this.tooltipTimeout = setTimeout(() => {
1941
+ if (this.hoveredCell &&
1942
+ this.hoveredCell.row === row &&
1943
+ this.hoveredCell.col === col) {
1944
+ this.showTooltip = true;
1945
+ }
1946
+ }, 500);
1947
+ }
1948
+ onCellMouseLeave() {
1949
+ if (this.tooltipTimeout) {
1950
+ clearTimeout(this.tooltipTimeout);
1951
+ this.tooltipTimeout = null;
1952
+ }
1953
+ this.showTooltip = false;
1954
+ this.hoveredCell = null;
1955
+ this.tooltipContent = '';
1956
+ }
1957
+ onCellMouseMove(event) {
1958
+ if (this.showTooltip) {
1959
+ this.tooltipPosition = {
1960
+ x: event.clientX + 10,
1961
+ y: event.clientY - 10,
1962
+ };
1963
+ }
1964
+ }
1965
+ // Métodos para inversão vertical dos tabs
1966
+ getTabGroups(tabs) {
1967
+ if (!tabs || tabs.length === 0)
1968
+ return [];
1969
+ const totalGroups = Math.ceil(tabs.length / 6);
1970
+ const groups = [];
1971
+ // Criar array de índices invertidos (último grupo primeiro)
1972
+ for (let i = totalGroups - 1; i >= 0; i--) {
1973
+ groups.push(i);
1974
+ }
1975
+ return groups;
1976
+ }
1977
+ getTabGroup(tabs, groupIndex) {
1978
+ if (!tabs || tabs.length === 0)
1979
+ return [];
1980
+ const startIndex = groupIndex * 6;
1981
+ const endIndex = Math.min(startIndex + 6, tabs.length);
1982
+ return tabs.slice(startIndex, endIndex);
1983
+ }
1984
+ getRealTabIndex(groupIndex, tabIndexInGroup) {
1985
+ if (!this.data.tabs?.tabsData)
1986
+ return 0;
1987
+ const totalGroups = Math.ceil(this.data.tabs.tabsData.length / 6);
1988
+ const realGroupIndex = totalGroups - 1 - groupIndex;
1989
+ return realGroupIndex * 6 + tabIndexInGroup;
1990
+ }
1991
+ onTableSelected(i, j) {
1992
+ if (!this.data.tabs?.tabsData || !this.data.tabs.method)
1993
+ return;
1994
+ this.selectedTab = this.getRealTabIndex(i, j);
1995
+ const tab = this.data.tabs.tabsData[this.selectedTab];
1996
+ if (tab) {
1997
+ this.data.tabs.method(tab, this.selectedTab);
1998
+ }
1999
+ }
2000
+ isTabSelected(originalIndex) {
2001
+ return this.selectedTab === originalIndex;
2002
+ }
2003
+ shouldShowActionButton() {
2004
+ if (!this.data?.actionButton) {
2005
+ return false;
2006
+ }
2007
+ if (!this.data.actionButton.condition) {
2008
+ return true;
2009
+ }
2010
+ try {
2011
+ return this.data.actionButton.condition(null) ?? true;
2012
+ }
2013
+ catch {
2014
+ return true;
2015
+ }
2016
+ }
2017
+ }
2018
+ TableComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: TableComponent, deps: [{ token: i1$1.Router }, { token: TableService }, { token: i1.AngularFirestore }], target: i0.ɵɵFactoryTarget.Component });
2019
+ TableComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.2.10", type: TableComponent, selector: "lib-table", inputs: { data: "data", downloadTable: "downloadTable" }, viewQueries: [{ propertyName: "paginator", first: true, predicate: MatPaginator, descendants: true }, { propertyName: "sort", first: true, predicate: MatSort, descendants: true }], ngImport: i0, template: "<div *ngIf=\"data\" class=\"card-body\">\r\n <div class=\"flex flex-col justify-between gap-6\">\r\n <!-- UNIFIED CONTROL PANEL: FILTERS, SORT & ACTIONS -->\r\n <div\r\n class=\"rounded-xl border border-gray-200 bg-white p-4 shadow-lg\"\r\n *ngIf=\"\r\n data.pagination === true &&\r\n (dropdownItems.length > 0 ||\r\n sortableDropdownItems.length > 0 ||\r\n data.actionButton)\r\n \"\r\n >\r\n <!-- PANEL HEADER: Title, Custom Action, and Global Actions -->\r\n <div\r\n class=\"mb-4 flex flex-col items-start justify-between gap-4 border-b-2 border-gray-200 pb-4 md:flex-row md:items-center\"\r\n >\r\n <!-- Left Side: Title & Main Action Button -->\r\n <div class=\"flex flex-wrap items-center gap-4\">\r\n <div class=\"flex items-center gap-2\">\r\n <i class=\"fa fa-filter text-xl text-blue-500\"></i>\r\n <span class=\"text-lg font-semibold text-gray-700\"\r\n >Filtros e A\u00E7\u00F5es</span\r\n >\r\n </div>\r\n <button\r\n *ngIf=\"data.actionButton && data.actionButton.condition\"\r\n [ngClass]=\"\r\n (data.actionButton.colorClass || 'bg-blue-500') +\r\n ' flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium text-white hover:opacity-70'\r\n \"\r\n [routerLink]=\"data.actionButton.routerLink\"\r\n (click)=\"\r\n data.actionButton.method ? data.actionButton.method($event) : null\r\n \"\r\n >\r\n <i\r\n *ngIf=\"data.actionButton.icon\"\r\n [class]=\"data.actionButton.icon\"\r\n ></i>\r\n {{ data.actionButton.label }}\r\n </button>\r\n </div>\r\n\r\n <!-- Right Side: Search, Reset, Export -->\r\n <div\r\n class=\"flex flex-wrap gap-3\"\r\n *ngIf=\"\r\n this.hasFilterableColumn === true || this.hasSortableColumn === true\r\n \"\r\n >\r\n <button\r\n (click)=\"search()\"\r\n type=\"button\"\r\n class=\"flex items-center gap-2 rounded-lg bg-green-600 px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-green-700\"\r\n matTooltip=\"Aplicar filtros\"\r\n >\r\n <i class=\"fa fa-search\"></i>\r\n Pesquisar\r\n </button>\r\n\r\n <button\r\n (click)=\"resetFilter()\"\r\n class=\"flex items-center gap-2 rounded-lg bg-red-500 px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-red-600\"\r\n matTooltip=\"Limpar filtros\"\r\n >\r\n <i class=\"fas fa-redo-alt\"></i>\r\n Resetar\r\n </button>\r\n\r\n <button\r\n *ngIf=\"data.download !== false && downloadTable\"\r\n class=\"flex items-center gap-2 rounded-lg bg-orange-500 px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-orange-600\"\r\n matTooltipPosition=\"above\"\r\n matTooltip=\"Exportar Tabela\"\r\n [disabled]=\"\r\n this.dataSource && this.dataSource.filteredData.length <= 0\r\n \"\r\n (click)=\"\r\n $any(arrange) && downloadTable !== undefined\r\n ? downloadTable($any(arrange), data.conditions || [])\r\n : null\r\n \"\r\n >\r\n <i class=\"fa fa-download\"></i>\r\n Exportar\r\n </button>\r\n </div>\r\n </div>\r\n\r\n <!-- FILTERS CONTENT (WITH REFINEMENTS) -->\r\n <div class=\"mb-4 space-y-3\" *ngIf=\"filtersForm.controls.length > 0\">\r\n <div\r\n [formGroup]=\"$any(filterGroup)\"\r\n *ngFor=\"let filterGroup of filtersForm.controls; let i = index\"\r\n class=\"flex flex-wrap items-center gap-3 rounded-lg border border-gray-200 p-2\"\r\n >\r\n <!-- FILTER TYPE SELECTOR -->\r\n <div class=\"min-w-[200px] flex-1\" *ngIf=\"dropdownItems.length > 0\">\r\n <mat-form-field appearance=\"outline\" class=\"w-full\">\r\n <mat-label>Tipo de filtro</mat-label>\r\n <mat-select\r\n placeholder=\"Selecione o tipo...\"\r\n formControlName=\"selectFilter\"\r\n (selectionChange)=\"onSelectFilterChange()\"\r\n >\r\n <mat-option *ngFor=\"let item of dropdownItems\" [value]=\"item\">\r\n <div class=\"flex items-center gap-2\">\r\n <i\r\n [class]=\"item.icon || 'fa fa-filter'\"\r\n class=\"text-sm text-blue-500\"\r\n ></i>\r\n <span>{{ item.title }}</span>\r\n </div>\r\n </mat-option>\r\n </mat-select>\r\n </mat-form-field>\r\n </div>\r\n\r\n <!-- TEXT FILTER -->\r\n <div\r\n class=\"min-w-[200px] flex-1\"\r\n *ngIf=\"\r\n $any(filterGroup).get('selectFilter')?.value?.arrange === 'filter'\r\n \"\r\n >\r\n <mat-form-field appearance=\"outline\" class=\"w-full\">\r\n <mat-label class=\"flex items-center gap-2\">\r\n <i class=\"fa fa-search text-gray-400\"></i>\r\n <span>{{\r\n $any(filterGroup).get(\"selectFilter\")?.value?.title ||\r\n \"Filtrar\"\r\n }}</span>\r\n </mat-label>\r\n <input\r\n (keyup.enter)=\"search()\"\r\n formControlName=\"typeFilter\"\r\n matInput\r\n placeholder=\"Digite para filtrar...\"\r\n #input\r\n />\r\n </mat-form-field>\r\n </div>\r\n\r\n <!-- DROPDOWN FILTER -->\r\n <div\r\n class=\"min-w-[200px] flex-1\"\r\n *ngIf=\"\r\n $any(filterGroup).get('selectFilter')?.value &&\r\n $any(filterGroup)\r\n .get('selectFilter')\r\n ?.value.hasOwnProperty('items')\r\n \"\r\n >\r\n <mat-form-field appearance=\"outline\" class=\"w-full\">\r\n <mat-label>{{\r\n $any(filterGroup).get(\"selectFilter\")?.value?.title ||\r\n \"Selecione\"\r\n }}</mat-label>\r\n <mat-select\r\n placeholder=\"Selecione...\"\r\n formControlName=\"selectItem\"\r\n multiple\r\n >\r\n <mat-option\r\n *ngFor=\"\r\n let item of $any(filterGroup).get('selectFilter')?.value\r\n .items\r\n \"\r\n [value]=\"item\"\r\n >\r\n {{ item.label }}\r\n </mat-option>\r\n </mat-select>\r\n </mat-form-field>\r\n </div>\r\n\r\n <!-- DATE FILTER -->\r\n <div\r\n class=\"min-w-[340px] flex-auto\"\r\n *ngIf=\"\r\n $any(filterGroup).get('selectFilter')?.value?.arrange ===\r\n 'filterByDate'\r\n \"\r\n >\r\n <div\r\n class=\"flex flex-col items-stretch gap-3 sm:flex-row sm:items-center\"\r\n >\r\n <mat-form-field appearance=\"outline\" class=\"flex-1\">\r\n <mat-label class=\"flex items-center gap-2\">\r\n <i class=\"fa fa-calendar text-gray-400\"></i>\r\n <span>Data Inicial</span>\r\n </mat-label>\r\n <input\r\n matInput\r\n (keyup.enter)=\"search()\"\r\n formControlName=\"initialDate\"\r\n [dropSpecialCharacters]=\"false\"\r\n mask=\"d0/M0/0000\"\r\n placeholder=\"DD/MM/AAAA\"\r\n maxlength=\"10\"\r\n />\r\n </mat-form-field>\r\n\r\n <mat-form-field appearance=\"outline\" class=\"flex-1\">\r\n <mat-label class=\"flex items-center gap-2\">\r\n <i class=\"fa fa-calendar text-gray-400\"></i>\r\n <span>Data Final</span>\r\n </mat-label>\r\n <input\r\n (keyup.enter)=\"search()\"\r\n matInput\r\n formControlName=\"finalDate\"\r\n [dropSpecialCharacters]=\"false\"\r\n mask=\"d0/M0/0000\"\r\n placeholder=\"DD/MM/AAAA\"\r\n maxlength=\"10\"\r\n />\r\n </mat-form-field>\r\n </div>\r\n </div>\r\n\r\n <!-- REMOVE FILTER BUTTON -->\r\n <div *ngIf=\"filtersForm.length > 1\" class=\"ml-auto flex-shrink-0\">\r\n <button\r\n (click)=\"removeFilter(i)\"\r\n class=\"flex h-10 w-10 items-center justify-center rounded-full transition-colors duration-300 hover:bg-red-100\"\r\n matTooltip=\"Remover filtro\"\r\n >\r\n <i class=\"fa fa-trash text-red-500 hover:text-red-600\"></i>\r\n </button>\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <!-- PANEL FOOTER: Add Filter & Sort -->\r\n <div\r\n class=\"-mb-2 flex flex-col items-center justify-between gap-4 border-t border-gray-200 pt-4 sm:flex-row\"\r\n >\r\n <!-- Add Filter Button -->\r\n <div *ngIf=\"dropdownItems.length > 0\">\r\n <button\r\n (click)=\"addFilter()\"\r\n class=\"transform rounded-full border-2 border-blue-300 bg-blue-50 px-6 py-2 text-sm font-medium text-blue-600 transition-all duration-300 hover:-translate-y-0.5 hover:border-blue-400 hover:bg-blue-100 hover:shadow-md\"\r\n matTooltip=\"Adicionar novo filtro\"\r\n >\r\n <i class=\"fa fa-plus mr-2\"></i>\r\n Adicionar Filtro\r\n </button>\r\n </div>\r\n\r\n <!-- Sort Dropdown -->\r\n <div\r\n class=\"w-full sm:w-auto sm:min-w-[250px]\"\r\n *ngIf=\"sortableDropdownItems.length > 0\"\r\n >\r\n <mat-form-field appearance=\"outline\" class=\"w-full\">\r\n <mat-label>Ordenar por</mat-label>\r\n <mat-select placeholder=\"Selecione...\" [formControl]=\"selectSort\">\r\n <mat-option\r\n *ngFor=\"let item of sortableDropdownItems\"\r\n [value]=\"item\"\r\n >\r\n <div class=\"flex items-center gap-2\">\r\n <i class=\"fa fa-sort-alpha-down text-cyan-600\"></i>\r\n <span>{{ item.title }}</span>\r\n </div>\r\n </mat-option>\r\n </mat-select>\r\n </mat-form-field>\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <!-- SIMPLE SEARCH (for non-paginated tables) -->\r\n <div\r\n class=\"rounded-xl border border-gray-200 bg-white p-4 shadow-lg\"\r\n *ngIf=\"data.pagination === false && hasFilterableColumn === true\"\r\n >\r\n <mat-form-field appearance=\"outline\" class=\"w-full\">\r\n <mat-label class=\"flex items-center gap-2\">\r\n <i class=\"fa fa-search text-blue-500\"></i>\r\n Buscar\r\n </mat-label>\r\n <input\r\n matInput\r\n (keyup.enter)=\"search()\"\r\n (keyup)=\"applyFilter(filterInput.value)\"\r\n placeholder=\"Digite para filtrar...\"\r\n #filterInput\r\n />\r\n <mat-icon matSuffix class=\"text-gray-500\">search</mat-icon>\r\n </mat-form-field>\r\n <button\r\n *ngIf=\"data.actionButton\"\r\n [ngClass]=\"\r\n (data.actionButton.colorClass || 'bg-blue-500') +\r\n ' float-right flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium text-white hover:opacity-70'\r\n \"\r\n [routerLink]=\"data.actionButton.routerLink\"\r\n (click)=\"\r\n data.actionButton.method ? data.actionButton.method($event) : null\r\n \"\r\n >\r\n <i *ngIf=\"data.actionButton.icon\" [class]=\"data.actionButton.icon\"></i>\r\n {{ data.actionButton.label }}\r\n </button>\r\n </div>\r\n\r\n <!-- FILTERS PANEL (for non-paginated tables) -->\r\n <div\r\n class=\"rounded-xl border border-gray-200 bg-white p-4 shadow-lg\"\r\n *ngIf=\"data.pagination === false && dropdownItems.length > 0\"\r\n >\r\n <!-- FILTERS CONTENT -->\r\n <div class=\"mb-4 space-y-3\" *ngIf=\"filtersForm.controls.length > 0\">\r\n <div\r\n [formGroup]=\"$any(filterGroup)\"\r\n *ngFor=\"let filterGroup of filtersForm.controls; let i = index\"\r\n class=\"flex flex-wrap items-center gap-3 rounded-lg border border-gray-200 p-2\"\r\n >\r\n <!-- FILTER TYPE SELECTOR -->\r\n <div class=\"min-w-[200px] flex-1\" *ngIf=\"dropdownItems.length > 0\">\r\n <mat-form-field appearance=\"outline\" class=\"w-full\">\r\n <mat-label>Tipo de filtro</mat-label>\r\n <mat-select\r\n placeholder=\"Selecione o tipo...\"\r\n formControlName=\"selectFilter\"\r\n (selectionChange)=\"onSelectFilterChange()\"\r\n >\r\n <mat-option *ngFor=\"let item of dropdownItems\" [value]=\"item\">\r\n <div class=\"flex items-center gap-2\">\r\n <i\r\n [class]=\"item.icon || 'fa fa-filter'\"\r\n class=\"text-sm text-blue-500\"\r\n ></i>\r\n <span>{{ item.title }}</span>\r\n </div>\r\n </mat-option>\r\n </mat-select>\r\n </mat-form-field>\r\n </div>\r\n\r\n <!-- TEXT FILTER -->\r\n <div\r\n class=\"min-w-[200px] flex-1\"\r\n *ngIf=\"\r\n $any(filterGroup).get('selectFilter')?.value?.arrange === 'filter'\r\n \"\r\n >\r\n <mat-form-field appearance=\"outline\" class=\"w-full\">\r\n <mat-label class=\"flex items-center gap-2\">\r\n <i class=\"fa fa-search text-gray-400\"></i>\r\n <span>{{\r\n $any(filterGroup).get(\"selectFilter\")?.value?.title ||\r\n \"Filtrar\"\r\n }}</span>\r\n </mat-label>\r\n <input\r\n (keyup.enter)=\"search()\"\r\n formControlName=\"typeFilter\"\r\n matInput\r\n placeholder=\"Digite para filtrar...\"\r\n #input\r\n />\r\n </mat-form-field>\r\n </div>\r\n\r\n <!-- DROPDOWN FILTER -->\r\n <div\r\n class=\"min-w-[200px] flex-1\"\r\n *ngIf=\"\r\n $any(filterGroup).get('selectFilter')?.value &&\r\n $any(filterGroup)\r\n .get('selectFilter')\r\n ?.value.hasOwnProperty('items')\r\n \"\r\n >\r\n <mat-form-field appearance=\"outline\" class=\"w-full\">\r\n <mat-label>{{\r\n $any(filterGroup).get(\"selectFilter\")?.value?.title ||\r\n \"Selecione\"\r\n }}</mat-label>\r\n <mat-select\r\n placeholder=\"Selecione...\"\r\n formControlName=\"selectItem\"\r\n multiple\r\n >\r\n <mat-option\r\n *ngFor=\"\r\n let item of $any(filterGroup).get('selectFilter')?.value\r\n .items\r\n \"\r\n [value]=\"item\"\r\n >\r\n {{ item.label }}\r\n </mat-option>\r\n </mat-select>\r\n </mat-form-field>\r\n </div>\r\n\r\n <!-- DATE FILTER -->\r\n <div\r\n class=\"min-w-[340px] flex-auto\"\r\n *ngIf=\"\r\n $any(filterGroup).get('selectFilter')?.value?.arrange ===\r\n 'filterByDate'\r\n \"\r\n >\r\n <div\r\n class=\"flex flex-col items-stretch gap-3 sm:flex-row sm:items-center\"\r\n >\r\n <mat-form-field appearance=\"outline\" class=\"flex-1\">\r\n <mat-label class=\"flex items-center gap-2\">\r\n <i class=\"fa fa-calendar text-gray-400\"></i>\r\n <span>Data Inicial</span>\r\n </mat-label>\r\n <input\r\n matInput\r\n (keyup.enter)=\"search()\"\r\n (blur)=\"onDateFilterChange()\"\r\n formControlName=\"initialDate\"\r\n [dropSpecialCharacters]=\"false\"\r\n mask=\"d0/M0/0000\"\r\n placeholder=\"DD/MM/AAAA\"\r\n maxlength=\"10\"\r\n />\r\n </mat-form-field>\r\n\r\n <mat-form-field appearance=\"outline\" class=\"flex-1\">\r\n <mat-label class=\"flex items-center gap-2\">\r\n <i class=\"fa fa-calendar text-gray-400\"></i>\r\n <span>Data Final</span>\r\n </mat-label>\r\n <input\r\n (keyup.enter)=\"search()\"\r\n (blur)=\"onDateFilterChange()\"\r\n matInput\r\n formControlName=\"finalDate\"\r\n [dropSpecialCharacters]=\"false\"\r\n mask=\"d0/M0/0000\"\r\n placeholder=\"DD/MM/AAAA\"\r\n maxlength=\"10\"\r\n />\r\n </mat-form-field>\r\n </div>\r\n </div>\r\n\r\n <!-- REMOVE FILTER BUTTON -->\r\n <div *ngIf=\"filtersForm.length > 1\" class=\"ml-auto flex-shrink-0\">\r\n <button\r\n (click)=\"removeFilter(i)\"\r\n class=\"flex h-10 w-10 items-center justify-center rounded-full transition-colors duration-300 hover:bg-red-100\"\r\n matTooltip=\"Remover filtro\"\r\n >\r\n <i class=\"fa fa-trash text-red-500 hover:text-red-600\"></i>\r\n </button>\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <!-- PANEL FOOTER: Add Filter & Actions -->\r\n <div\r\n class=\"-mb-2 flex flex-col items-center justify-between gap-4 border-t border-gray-200 pt-4 sm:flex-row\"\r\n >\r\n <!-- Add Filter Button -->\r\n <div *ngIf=\"dropdownItems.length > 0\">\r\n <button\r\n (click)=\"addFilter()\"\r\n class=\"transform rounded-full border-2 border-blue-300 bg-blue-50 px-6 py-2 text-sm font-medium text-blue-600 transition-all duration-300 hover:-translate-y-0.5 hover:border-blue-400 hover:bg-blue-100 hover:shadow-md\"\r\n matTooltip=\"Adicionar novo filtro\"\r\n >\r\n <i class=\"fa fa-plus mr-2\"></i>\r\n Adicionar Filtro\r\n </button>\r\n </div>\r\n\r\n <!-- Action Buttons -->\r\n <div class=\"flex flex-wrap gap-3\">\r\n <button\r\n (click)=\"search()\"\r\n type=\"button\"\r\n class=\"flex items-center gap-2 rounded-lg bg-green-600 px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-green-700\"\r\n matTooltip=\"Aplicar filtros\"\r\n >\r\n <i class=\"fa fa-search\"></i>\r\n Aplicar\r\n </button>\r\n\r\n <button\r\n (click)=\"resetFilter()\"\r\n class=\"flex items-center gap-2 rounded-lg bg-red-500 px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-red-600\"\r\n matTooltip=\"Limpar filtros\"\r\n >\r\n <i class=\"fas fa-redo-alt\"></i>\r\n Resetar\r\n </button>\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <div class=\"flex flex-col\">\r\n <div\r\n class=\"mx-auto flex flex-col\"\r\n *ngIf=\"data.tabs && data.tabs.tabsData && data.tabs.tabsData.length > 0\"\r\n >\r\n <!-- Calcular quantos grupos de 6 tabs existem -->\r\n <ng-container\r\n *ngFor=\"\r\n let groupIndex of getTabGroups(data.tabs.tabsData);\r\n let i = index\r\n \"\r\n >\r\n <div class=\"mx-auto flex flex-row\">\r\n <ng-container\r\n *ngFor=\"\r\n let tab of getTabGroup(data.tabs.tabsData, groupIndex);\r\n let j = index\r\n \"\r\n >\r\n <button\r\n class=\"border-2 border-gray-300 bg-gray-200 px-4 py-2 font-medium transition hover:brightness-95\"\r\n [ngClass]=\"\r\n isTabSelected(getRealTabIndex(i, j))\r\n ? 'border-b-0 brightness-110'\r\n : ''\r\n \"\r\n (click)=\"onTableSelected(i, j)\"\r\n >\r\n {{ tab.label }}\r\n <span\r\n *ngIf=\"tab.counter !== undefined\"\r\n class=\"ml-2 text-xs font-bold\"\r\n [ngClass]=\"tab.counterClass\"\r\n >\r\n {{ tab.counter }}\r\n </span>\r\n </button>\r\n </ng-container>\r\n </div>\r\n </ng-container>\r\n </div>\r\n <div class=\"mat-elevation-z8 w-full overflow-x-auto rounded-xl\">\r\n <table\r\n mat-table\r\n [dataSource]=\"dataSource\"\r\n matSort\r\n #sort=\"matSort\"\r\n matSortActive=\"createdAt\"\r\n matSortDirection=\"desc\"\r\n >\r\n <ng-container\r\n *ngFor=\"let col of data.displayedColumns\"\r\n matColumnDef=\"{{ col.property }}\"\r\n >\r\n <ng-container *matHeaderCellDef>\r\n <!-- IF THE COLUMN IS NOT SORTABLE, THEN DON'T SHOW THE SORT BUTTONS -->\r\n <th\r\n *ngIf=\"!col.isSortable || data.pagination === true\"\r\n mat-header-cell\r\n [ngClass]=\"\r\n (data.color?.bg ? ' ' + $any(data.color).bg : '') +\r\n (data.color?.text ? ' ' + $any(data.color).text : '')\r\n \"\r\n >\r\n {{ col.title }}\r\n </th>\r\n <!-- IF THE COLUMN IS SORTABLE, THEN SHOW THE SORT BUTTONS -->\r\n <th\r\n *ngIf=\"col.isSortable && data.pagination === false\"\r\n mat-header-cell\r\n mat-sort-header\r\n [ngClass]=\"\r\n (data.color?.bg ? ' ' + $any(data.color).bg : '') +\r\n (data.color?.text ? ' ' + $any(data.color).text : '')\r\n \"\r\n >\r\n {{ col.title }}\r\n </th>\r\n <td\r\n mat-cell\r\n *matCellDef=\"let row\"\r\n (click)=\"col.method ? col.method(row) : null\"\r\n (mouseenter)=\"onCellMouseEnter($event, row, col)\"\r\n (mouseleave)=\"onCellMouseLeave()\"\r\n (mousemove)=\"onCellMouseMove($event)\"\r\n >\r\n <!-- CHECK IF THE COLUMN MUST BE DISPLAYED -->\r\n <span *ngIf=\"!col.image && !col.iconClass && !col.method\">\r\n <ng-container>\r\n <span\r\n *ngIf=\"\r\n col.charLimit &&\r\n row[col.property] &&\r\n row[col.property].length > col.charLimit;\r\n else withinLimit\r\n \"\r\n >\r\n <a\r\n *ngIf=\"col.hasLink === true\"\r\n [href]=\"row[col.property]\"\r\n target=\"_blank\"\r\n >\r\n {{ getDisplayValue(col, row) }}\r\n </a>\r\n <a\r\n *ngIf=\"col.hasLink && isString(col.hasLink)\"\r\n [href]=\"col.hasLink\"\r\n target=\"_blank\"\r\n >\r\n {{ getDisplayValue(col, row) }}\r\n </a>\r\n <span\r\n *ngIf=\"col.hasLink !== true && !isString(col.hasLink)\"\r\n >\r\n {{ getDisplayValue(col, row) }}\r\n </span>\r\n </span>\r\n </ng-container>\r\n <ng-template #withinLimit>\r\n <a\r\n *ngIf=\"col.hasLink === true\"\r\n [href]=\"row[col.property]\"\r\n target=\"_blank\"\r\n >\r\n {{ getDisplayValue(col, row, true) }}\r\n </a>\r\n <a\r\n *ngIf=\"col.hasLink && isString(col.hasLink)\"\r\n [href]=\"col.hasLink\"\r\n target=\"_blank\"\r\n >\r\n {{ getDisplayValue(col, row, true) }}\r\n </a>\r\n <span\r\n *ngIf=\"col.hasLink !== true && !isString(col.hasLink)\"\r\n >\r\n {{ getDisplayValue(col, row, true) }}\r\n </span>\r\n </ng-template>\r\n </span>\r\n <!------------------- IMAGE ------------------>\r\n <img\r\n *ngIf=\"\r\n col.image && col.image.path && !col.iconClass && !col.method\r\n \"\r\n [src]=\"col.image.path + '/' + row[col.property]\"\r\n [ngClass]=\"col.image.class\"\r\n alt=\"Imagem\"\r\n />\r\n <img\r\n *ngIf=\"\r\n col.image && col.image.url && !col.iconClass && !col.method\r\n \"\r\n [src]=\"row[col.property]\"\r\n [ngClass]=\"col.image.class\"\r\n alt=\"Imagem\"\r\n />\r\n <ng-container *ngIf=\"col.iconClass\">\r\n <button\r\n *ngFor=\"let iconClass of col.iconClass\"\r\n (click)=\"\r\n iconClass.buttonMethod\r\n ? iconClass.buttonMethod(row, $event)\r\n : $event.stopPropagation()\r\n \"\r\n >\r\n <span\r\n [ngClass]=\"iconClass.class\"\r\n *ngIf=\"\r\n iconClass.condition === undefined ||\r\n (iconClass.condition !== undefined &&\r\n $any(iconClass.condition)(row))\r\n \"\r\n >{{ iconClass.text }}</span\r\n >\r\n </button>\r\n </ng-container>\r\n </td>\r\n </ng-container>\r\n </ng-container>\r\n\r\n <tr mat-header-row *matHeaderRowDef=\"columnProperties\"></tr>\r\n <tr\r\n [ngClass]=\"{\r\n 'example-element-row': data.isNotClickable === true,\r\n 'example-element-row cursor-pointer': !data.isNotClickable\r\n }\"\r\n mat-row\r\n *matRowDef=\"let row; columns: columnProperties\"\r\n (click)=\"goToDetails(row)\"\r\n ></tr>\r\n\r\n <!-- ROW SHOWN WHEN THERE IS NO MATCHING DATA. -->\r\n <tr class=\"mat-row\" *matNoDataRow>\r\n <td *ngIf=\"!isLoading\" class=\"mat-cell p-4\" colspan=\"4\">\r\n Nenhum resultado encontrado para a busca\r\n </td>\r\n </tr>\r\n </table>\r\n\r\n <div class=\"flex justify-center\" *ngIf=\"isLoading\">\r\n <mat-spinner></mat-spinner>\r\n </div>\r\n\r\n <div class=\"paginator-container\">\r\n <mat-paginator\r\n #paginator\r\n [pageSizeOptions]=\"[25, 50, 100]\"\r\n [pageSize]=\"pageSize\"\r\n [length]=\"totalItems\"\r\n showFirstLastButtons\r\n aria-label=\"Select page of periodic elements\"\r\n (page)=\"onPageChange($event)\"\r\n [ngClass]=\"{\r\n 'hide-length':\r\n ['filter', 'filterByDate', 'equals'].includes(\r\n this.currentArrange\r\n ) || this.data.filterFn,\r\n 'hide-next-button': !hasNextPage && data.pagination === true,\r\n 'hide-last-button':\r\n (!hasNextPage && data.pagination === true) || this.data.filterFn\r\n }\"\r\n >\r\n </mat-paginator>\r\n <div\r\n *ngIf=\"\r\n !isLoading &&\r\n dataSource?.data &&\r\n dataSource.data.length > 0 &&\r\n data?.filterFn\r\n \"\r\n class=\"page-number-display\"\r\n >\r\n {{ currentPageNumber }}\r\n </div>\r\n </div>\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <!-- TOOLTIP PERSONALIZADO -->\r\n <div\r\n *ngIf=\"showTooltip\"\r\n class=\"fixed z-50 max-w-md break-words rounded-lg bg-gray-800 px-3 py-2 text-sm text-white shadow-lg\"\r\n [style.left.px]=\"tooltipPosition.x\"\r\n [style.top.px]=\"tooltipPosition.y\"\r\n [style.pointer-events]=\"'none'\"\r\n >\r\n {{ tooltipContent }}\r\n </div>\r\n</div>\r\n", styles: ["::ng-deep .hide-length .mat-mdc-paginator-range-label{display:none}::ng-deep .hide-next-button .mat-mdc-tooltip-trigger.mat-mdc-paginator-navigation-next.mdc-icon-button.mat-mdc-icon-button.mat-unthemed.mat-mdc-button-base{visibility:hidden}::ng-deep .hide-next-button .mat-mdc-tooltip-trigger.mat-mdc-paginator-navigation-last.mdc-icon-button.mat-mdc-icon-button.mat-unthemed.mat-mdc-button-base.ng-star-inserted{visibility:hidden}::ng-deep .mat-mdc-text-field-wrapper.mdc-text-field.ng-tns-c162-1.mdc-text-field--filled{width:25dvw}::ng-deep .custom-filter .mat-mdc-text-field-wrapper{width:20dvw;max-width:300px}\n"], dependencies: [{ kind: "directive", type: i4.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "directive", type: i4.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "directive", type: i4.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i5.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i5.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i5.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i5.MaxLengthValidator, selector: "[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]", inputs: ["maxlength"] }, { kind: "directive", type: i5.FormControlDirective, selector: "[formControl]", inputs: ["formControl", "disabled", "ngModel"], outputs: ["ngModelChange"], exportAs: ["ngForm"] }, { kind: "directive", type: i5.FormGroupDirective, selector: "[formGroup]", inputs: ["formGroup"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "directive", type: i5.FormControlName, selector: "[formControlName]", inputs: ["formControlName", "disabled", "ngModel"], outputs: ["ngModelChange"] }, { kind: "directive", type: i1$1.RouterLink, selector: "[routerLink]", inputs: ["target", "queryParams", "fragment", "queryParamsHandling", "state", "relativeTo", "preserveFragment", "skipLocationChange", "replaceUrl", "routerLink"] }, { kind: "component", type: i6.MatTable, selector: "mat-table, table[mat-table]", exportAs: ["matTable"] }, { kind: "directive", type: i6.MatHeaderCellDef, selector: "[matHeaderCellDef]" }, { kind: "directive", type: i6.MatHeaderRowDef, selector: "[matHeaderRowDef]", inputs: ["matHeaderRowDef", "matHeaderRowDefSticky"] }, { kind: "directive", type: i6.MatColumnDef, selector: "[matColumnDef]", inputs: ["sticky", "matColumnDef"] }, { kind: "directive", type: i6.MatCellDef, selector: "[matCellDef]" }, { kind: "directive", type: i6.MatRowDef, selector: "[matRowDef]", inputs: ["matRowDefColumns", "matRowDefWhen"] }, { kind: "directive", type: i6.MatHeaderCell, selector: "mat-header-cell, th[mat-header-cell]" }, { kind: "directive", type: i6.MatCell, selector: "mat-cell, td[mat-cell]" }, { kind: "component", type: i6.MatHeaderRow, selector: "mat-header-row, tr[mat-header-row]", exportAs: ["matHeaderRow"] }, { kind: "component", type: i6.MatRow, selector: "mat-row, tr[mat-row]", exportAs: ["matRow"] }, { kind: "directive", type: i6.MatNoDataRow, selector: "ng-template[matNoDataRow]" }, { kind: "component", type: i7.MatPaginator, selector: "mat-paginator", inputs: ["disabled"], exportAs: ["matPaginator"] }, { kind: "directive", type: i8.MatSort, selector: "[matSort]", inputs: ["matSortDisabled", "matSortActive", "matSortStart", "matSortDirection", "matSortDisableClear"], outputs: ["matSortChange"], exportAs: ["matSort"] }, { kind: "component", type: i8.MatSortHeader, selector: "[mat-sort-header]", inputs: ["disabled", "mat-sort-header", "arrowPosition", "start", "sortActionDescription", "disableClear"], exportAs: ["matSortHeader"] }, { kind: "component", type: i9.MatFormField, selector: "mat-form-field", inputs: ["hideRequiredMarker", "color", "floatLabel", "appearance", "subscriptSizing", "hintLabel"], exportAs: ["matFormField"] }, { kind: "directive", type: i9.MatLabel, selector: "mat-label" }, { kind: "directive", type: i9.MatSuffix, selector: "[matSuffix], [matIconSuffix], [matTextSuffix]", inputs: ["matTextSuffix"] }, { kind: "directive", type: i10.MatInput, selector: "input[matInput], textarea[matInput], select[matNativeControl], input[matNativeControl], textarea[matNativeControl]", inputs: ["disabled", "id", "placeholder", "name", "required", "type", "errorStateMatcher", "aria-describedby", "value", "readonly"], exportAs: ["matInput"] }, { kind: "component", type: i11.MatSelect, selector: "mat-select", inputs: ["disabled", "disableRipple", "tabIndex", "hideSingleSelectionIndicator"], exportAs: ["matSelect"] }, { kind: "component", type: i12.MatOption, selector: "mat-option", exportAs: ["matOption"] }, { kind: "directive", type: i13.MatTooltip, selector: "[matTooltip]", exportAs: ["matTooltip"] }, { kind: "component", type: i14.MatProgressSpinner, selector: "mat-progress-spinner, mat-spinner", inputs: ["color", "mode", "value", "diameter", "strokeWidth"], exportAs: ["matProgressSpinner"] }, { kind: "component", type: i15.MatIcon, selector: "mat-icon", inputs: ["color", "inline", "svgIcon", "fontSet", "fontIcon"], exportAs: ["matIcon"] }, { kind: "directive", type: i16.NgxMaskDirective, selector: "input[mask], textarea[mask]", inputs: ["mask", "specialCharacters", "patterns", "prefix", "suffix", "thousandSeparator", "decimalMarker", "dropSpecialCharacters", "hiddenInput", "showMaskTyped", "placeHolderCharacter", "shownMaskExpression", "showTemplate", "clearIfNotMatch", "validation", "separatorLimit", "allowNegativeNumbers", "leadZeroDateTime", "leadZero", "triggerOnMaskChange", "apm", "inputTransformFn", "outputTransformFn", "keepCharacterPositions"], outputs: ["maskFilled"], exportAs: ["mask", "ngxMask"] }] });
2020
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: TableComponent, decorators: [{
2021
+ type: Component,
2022
+ args: [{ selector: 'lib-table', template: "<div *ngIf=\"data\" class=\"card-body\">\r\n <div class=\"flex flex-col justify-between gap-6\">\r\n <!-- UNIFIED CONTROL PANEL: FILTERS, SORT & ACTIONS -->\r\n <div\r\n class=\"rounded-xl border border-gray-200 bg-white p-4 shadow-lg\"\r\n *ngIf=\"\r\n data.pagination === true &&\r\n (dropdownItems.length > 0 ||\r\n sortableDropdownItems.length > 0 ||\r\n data.actionButton)\r\n \"\r\n >\r\n <!-- PANEL HEADER: Title, Custom Action, and Global Actions -->\r\n <div\r\n class=\"mb-4 flex flex-col items-start justify-between gap-4 border-b-2 border-gray-200 pb-4 md:flex-row md:items-center\"\r\n >\r\n <!-- Left Side: Title & Main Action Button -->\r\n <div class=\"flex flex-wrap items-center gap-4\">\r\n <div class=\"flex items-center gap-2\">\r\n <i class=\"fa fa-filter text-xl text-blue-500\"></i>\r\n <span class=\"text-lg font-semibold text-gray-700\"\r\n >Filtros e A\u00E7\u00F5es</span\r\n >\r\n </div>\r\n <button\r\n *ngIf=\"data.actionButton && data.actionButton.condition\"\r\n [ngClass]=\"\r\n (data.actionButton.colorClass || 'bg-blue-500') +\r\n ' flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium text-white hover:opacity-70'\r\n \"\r\n [routerLink]=\"data.actionButton.routerLink\"\r\n (click)=\"\r\n data.actionButton.method ? data.actionButton.method($event) : null\r\n \"\r\n >\r\n <i\r\n *ngIf=\"data.actionButton.icon\"\r\n [class]=\"data.actionButton.icon\"\r\n ></i>\r\n {{ data.actionButton.label }}\r\n </button>\r\n </div>\r\n\r\n <!-- Right Side: Search, Reset, Export -->\r\n <div\r\n class=\"flex flex-wrap gap-3\"\r\n *ngIf=\"\r\n this.hasFilterableColumn === true || this.hasSortableColumn === true\r\n \"\r\n >\r\n <button\r\n (click)=\"search()\"\r\n type=\"button\"\r\n class=\"flex items-center gap-2 rounded-lg bg-green-600 px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-green-700\"\r\n matTooltip=\"Aplicar filtros\"\r\n >\r\n <i class=\"fa fa-search\"></i>\r\n Pesquisar\r\n </button>\r\n\r\n <button\r\n (click)=\"resetFilter()\"\r\n class=\"flex items-center gap-2 rounded-lg bg-red-500 px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-red-600\"\r\n matTooltip=\"Limpar filtros\"\r\n >\r\n <i class=\"fas fa-redo-alt\"></i>\r\n Resetar\r\n </button>\r\n\r\n <button\r\n *ngIf=\"data.download !== false && downloadTable\"\r\n class=\"flex items-center gap-2 rounded-lg bg-orange-500 px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-orange-600\"\r\n matTooltipPosition=\"above\"\r\n matTooltip=\"Exportar Tabela\"\r\n [disabled]=\"\r\n this.dataSource && this.dataSource.filteredData.length <= 0\r\n \"\r\n (click)=\"\r\n $any(arrange) && downloadTable !== undefined\r\n ? downloadTable($any(arrange), data.conditions || [])\r\n : null\r\n \"\r\n >\r\n <i class=\"fa fa-download\"></i>\r\n Exportar\r\n </button>\r\n </div>\r\n </div>\r\n\r\n <!-- FILTERS CONTENT (WITH REFINEMENTS) -->\r\n <div class=\"mb-4 space-y-3\" *ngIf=\"filtersForm.controls.length > 0\">\r\n <div\r\n [formGroup]=\"$any(filterGroup)\"\r\n *ngFor=\"let filterGroup of filtersForm.controls; let i = index\"\r\n class=\"flex flex-wrap items-center gap-3 rounded-lg border border-gray-200 p-2\"\r\n >\r\n <!-- FILTER TYPE SELECTOR -->\r\n <div class=\"min-w-[200px] flex-1\" *ngIf=\"dropdownItems.length > 0\">\r\n <mat-form-field appearance=\"outline\" class=\"w-full\">\r\n <mat-label>Tipo de filtro</mat-label>\r\n <mat-select\r\n placeholder=\"Selecione o tipo...\"\r\n formControlName=\"selectFilter\"\r\n (selectionChange)=\"onSelectFilterChange()\"\r\n >\r\n <mat-option *ngFor=\"let item of dropdownItems\" [value]=\"item\">\r\n <div class=\"flex items-center gap-2\">\r\n <i\r\n [class]=\"item.icon || 'fa fa-filter'\"\r\n class=\"text-sm text-blue-500\"\r\n ></i>\r\n <span>{{ item.title }}</span>\r\n </div>\r\n </mat-option>\r\n </mat-select>\r\n </mat-form-field>\r\n </div>\r\n\r\n <!-- TEXT FILTER -->\r\n <div\r\n class=\"min-w-[200px] flex-1\"\r\n *ngIf=\"\r\n $any(filterGroup).get('selectFilter')?.value?.arrange === 'filter'\r\n \"\r\n >\r\n <mat-form-field appearance=\"outline\" class=\"w-full\">\r\n <mat-label class=\"flex items-center gap-2\">\r\n <i class=\"fa fa-search text-gray-400\"></i>\r\n <span>{{\r\n $any(filterGroup).get(\"selectFilter\")?.value?.title ||\r\n \"Filtrar\"\r\n }}</span>\r\n </mat-label>\r\n <input\r\n (keyup.enter)=\"search()\"\r\n formControlName=\"typeFilter\"\r\n matInput\r\n placeholder=\"Digite para filtrar...\"\r\n #input\r\n />\r\n </mat-form-field>\r\n </div>\r\n\r\n <!-- DROPDOWN FILTER -->\r\n <div\r\n class=\"min-w-[200px] flex-1\"\r\n *ngIf=\"\r\n $any(filterGroup).get('selectFilter')?.value &&\r\n $any(filterGroup)\r\n .get('selectFilter')\r\n ?.value.hasOwnProperty('items')\r\n \"\r\n >\r\n <mat-form-field appearance=\"outline\" class=\"w-full\">\r\n <mat-label>{{\r\n $any(filterGroup).get(\"selectFilter\")?.value?.title ||\r\n \"Selecione\"\r\n }}</mat-label>\r\n <mat-select\r\n placeholder=\"Selecione...\"\r\n formControlName=\"selectItem\"\r\n multiple\r\n >\r\n <mat-option\r\n *ngFor=\"\r\n let item of $any(filterGroup).get('selectFilter')?.value\r\n .items\r\n \"\r\n [value]=\"item\"\r\n >\r\n {{ item.label }}\r\n </mat-option>\r\n </mat-select>\r\n </mat-form-field>\r\n </div>\r\n\r\n <!-- DATE FILTER -->\r\n <div\r\n class=\"min-w-[340px] flex-auto\"\r\n *ngIf=\"\r\n $any(filterGroup).get('selectFilter')?.value?.arrange ===\r\n 'filterByDate'\r\n \"\r\n >\r\n <div\r\n class=\"flex flex-col items-stretch gap-3 sm:flex-row sm:items-center\"\r\n >\r\n <mat-form-field appearance=\"outline\" class=\"flex-1\">\r\n <mat-label class=\"flex items-center gap-2\">\r\n <i class=\"fa fa-calendar text-gray-400\"></i>\r\n <span>Data Inicial</span>\r\n </mat-label>\r\n <input\r\n matInput\r\n (keyup.enter)=\"search()\"\r\n formControlName=\"initialDate\"\r\n [dropSpecialCharacters]=\"false\"\r\n mask=\"d0/M0/0000\"\r\n placeholder=\"DD/MM/AAAA\"\r\n maxlength=\"10\"\r\n />\r\n </mat-form-field>\r\n\r\n <mat-form-field appearance=\"outline\" class=\"flex-1\">\r\n <mat-label class=\"flex items-center gap-2\">\r\n <i class=\"fa fa-calendar text-gray-400\"></i>\r\n <span>Data Final</span>\r\n </mat-label>\r\n <input\r\n (keyup.enter)=\"search()\"\r\n matInput\r\n formControlName=\"finalDate\"\r\n [dropSpecialCharacters]=\"false\"\r\n mask=\"d0/M0/0000\"\r\n placeholder=\"DD/MM/AAAA\"\r\n maxlength=\"10\"\r\n />\r\n </mat-form-field>\r\n </div>\r\n </div>\r\n\r\n <!-- REMOVE FILTER BUTTON -->\r\n <div *ngIf=\"filtersForm.length > 1\" class=\"ml-auto flex-shrink-0\">\r\n <button\r\n (click)=\"removeFilter(i)\"\r\n class=\"flex h-10 w-10 items-center justify-center rounded-full transition-colors duration-300 hover:bg-red-100\"\r\n matTooltip=\"Remover filtro\"\r\n >\r\n <i class=\"fa fa-trash text-red-500 hover:text-red-600\"></i>\r\n </button>\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <!-- PANEL FOOTER: Add Filter & Sort -->\r\n <div\r\n class=\"-mb-2 flex flex-col items-center justify-between gap-4 border-t border-gray-200 pt-4 sm:flex-row\"\r\n >\r\n <!-- Add Filter Button -->\r\n <div *ngIf=\"dropdownItems.length > 0\">\r\n <button\r\n (click)=\"addFilter()\"\r\n class=\"transform rounded-full border-2 border-blue-300 bg-blue-50 px-6 py-2 text-sm font-medium text-blue-600 transition-all duration-300 hover:-translate-y-0.5 hover:border-blue-400 hover:bg-blue-100 hover:shadow-md\"\r\n matTooltip=\"Adicionar novo filtro\"\r\n >\r\n <i class=\"fa fa-plus mr-2\"></i>\r\n Adicionar Filtro\r\n </button>\r\n </div>\r\n\r\n <!-- Sort Dropdown -->\r\n <div\r\n class=\"w-full sm:w-auto sm:min-w-[250px]\"\r\n *ngIf=\"sortableDropdownItems.length > 0\"\r\n >\r\n <mat-form-field appearance=\"outline\" class=\"w-full\">\r\n <mat-label>Ordenar por</mat-label>\r\n <mat-select placeholder=\"Selecione...\" [formControl]=\"selectSort\">\r\n <mat-option\r\n *ngFor=\"let item of sortableDropdownItems\"\r\n [value]=\"item\"\r\n >\r\n <div class=\"flex items-center gap-2\">\r\n <i class=\"fa fa-sort-alpha-down text-cyan-600\"></i>\r\n <span>{{ item.title }}</span>\r\n </div>\r\n </mat-option>\r\n </mat-select>\r\n </mat-form-field>\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <!-- SIMPLE SEARCH (for non-paginated tables) -->\r\n <div\r\n class=\"rounded-xl border border-gray-200 bg-white p-4 shadow-lg\"\r\n *ngIf=\"data.pagination === false && hasFilterableColumn === true\"\r\n >\r\n <mat-form-field appearance=\"outline\" class=\"w-full\">\r\n <mat-label class=\"flex items-center gap-2\">\r\n <i class=\"fa fa-search text-blue-500\"></i>\r\n Buscar\r\n </mat-label>\r\n <input\r\n matInput\r\n (keyup.enter)=\"search()\"\r\n (keyup)=\"applyFilter(filterInput.value)\"\r\n placeholder=\"Digite para filtrar...\"\r\n #filterInput\r\n />\r\n <mat-icon matSuffix class=\"text-gray-500\">search</mat-icon>\r\n </mat-form-field>\r\n <button\r\n *ngIf=\"data.actionButton\"\r\n [ngClass]=\"\r\n (data.actionButton.colorClass || 'bg-blue-500') +\r\n ' float-right flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium text-white hover:opacity-70'\r\n \"\r\n [routerLink]=\"data.actionButton.routerLink\"\r\n (click)=\"\r\n data.actionButton.method ? data.actionButton.method($event) : null\r\n \"\r\n >\r\n <i *ngIf=\"data.actionButton.icon\" [class]=\"data.actionButton.icon\"></i>\r\n {{ data.actionButton.label }}\r\n </button>\r\n </div>\r\n\r\n <!-- FILTERS PANEL (for non-paginated tables) -->\r\n <div\r\n class=\"rounded-xl border border-gray-200 bg-white p-4 shadow-lg\"\r\n *ngIf=\"data.pagination === false && dropdownItems.length > 0\"\r\n >\r\n <!-- FILTERS CONTENT -->\r\n <div class=\"mb-4 space-y-3\" *ngIf=\"filtersForm.controls.length > 0\">\r\n <div\r\n [formGroup]=\"$any(filterGroup)\"\r\n *ngFor=\"let filterGroup of filtersForm.controls; let i = index\"\r\n class=\"flex flex-wrap items-center gap-3 rounded-lg border border-gray-200 p-2\"\r\n >\r\n <!-- FILTER TYPE SELECTOR -->\r\n <div class=\"min-w-[200px] flex-1\" *ngIf=\"dropdownItems.length > 0\">\r\n <mat-form-field appearance=\"outline\" class=\"w-full\">\r\n <mat-label>Tipo de filtro</mat-label>\r\n <mat-select\r\n placeholder=\"Selecione o tipo...\"\r\n formControlName=\"selectFilter\"\r\n (selectionChange)=\"onSelectFilterChange()\"\r\n >\r\n <mat-option *ngFor=\"let item of dropdownItems\" [value]=\"item\">\r\n <div class=\"flex items-center gap-2\">\r\n <i\r\n [class]=\"item.icon || 'fa fa-filter'\"\r\n class=\"text-sm text-blue-500\"\r\n ></i>\r\n <span>{{ item.title }}</span>\r\n </div>\r\n </mat-option>\r\n </mat-select>\r\n </mat-form-field>\r\n </div>\r\n\r\n <!-- TEXT FILTER -->\r\n <div\r\n class=\"min-w-[200px] flex-1\"\r\n *ngIf=\"\r\n $any(filterGroup).get('selectFilter')?.value?.arrange === 'filter'\r\n \"\r\n >\r\n <mat-form-field appearance=\"outline\" class=\"w-full\">\r\n <mat-label class=\"flex items-center gap-2\">\r\n <i class=\"fa fa-search text-gray-400\"></i>\r\n <span>{{\r\n $any(filterGroup).get(\"selectFilter\")?.value?.title ||\r\n \"Filtrar\"\r\n }}</span>\r\n </mat-label>\r\n <input\r\n (keyup.enter)=\"search()\"\r\n formControlName=\"typeFilter\"\r\n matInput\r\n placeholder=\"Digite para filtrar...\"\r\n #input\r\n />\r\n </mat-form-field>\r\n </div>\r\n\r\n <!-- DROPDOWN FILTER -->\r\n <div\r\n class=\"min-w-[200px] flex-1\"\r\n *ngIf=\"\r\n $any(filterGroup).get('selectFilter')?.value &&\r\n $any(filterGroup)\r\n .get('selectFilter')\r\n ?.value.hasOwnProperty('items')\r\n \"\r\n >\r\n <mat-form-field appearance=\"outline\" class=\"w-full\">\r\n <mat-label>{{\r\n $any(filterGroup).get(\"selectFilter\")?.value?.title ||\r\n \"Selecione\"\r\n }}</mat-label>\r\n <mat-select\r\n placeholder=\"Selecione...\"\r\n formControlName=\"selectItem\"\r\n multiple\r\n >\r\n <mat-option\r\n *ngFor=\"\r\n let item of $any(filterGroup).get('selectFilter')?.value\r\n .items\r\n \"\r\n [value]=\"item\"\r\n >\r\n {{ item.label }}\r\n </mat-option>\r\n </mat-select>\r\n </mat-form-field>\r\n </div>\r\n\r\n <!-- DATE FILTER -->\r\n <div\r\n class=\"min-w-[340px] flex-auto\"\r\n *ngIf=\"\r\n $any(filterGroup).get('selectFilter')?.value?.arrange ===\r\n 'filterByDate'\r\n \"\r\n >\r\n <div\r\n class=\"flex flex-col items-stretch gap-3 sm:flex-row sm:items-center\"\r\n >\r\n <mat-form-field appearance=\"outline\" class=\"flex-1\">\r\n <mat-label class=\"flex items-center gap-2\">\r\n <i class=\"fa fa-calendar text-gray-400\"></i>\r\n <span>Data Inicial</span>\r\n </mat-label>\r\n <input\r\n matInput\r\n (keyup.enter)=\"search()\"\r\n (blur)=\"onDateFilterChange()\"\r\n formControlName=\"initialDate\"\r\n [dropSpecialCharacters]=\"false\"\r\n mask=\"d0/M0/0000\"\r\n placeholder=\"DD/MM/AAAA\"\r\n maxlength=\"10\"\r\n />\r\n </mat-form-field>\r\n\r\n <mat-form-field appearance=\"outline\" class=\"flex-1\">\r\n <mat-label class=\"flex items-center gap-2\">\r\n <i class=\"fa fa-calendar text-gray-400\"></i>\r\n <span>Data Final</span>\r\n </mat-label>\r\n <input\r\n (keyup.enter)=\"search()\"\r\n (blur)=\"onDateFilterChange()\"\r\n matInput\r\n formControlName=\"finalDate\"\r\n [dropSpecialCharacters]=\"false\"\r\n mask=\"d0/M0/0000\"\r\n placeholder=\"DD/MM/AAAA\"\r\n maxlength=\"10\"\r\n />\r\n </mat-form-field>\r\n </div>\r\n </div>\r\n\r\n <!-- REMOVE FILTER BUTTON -->\r\n <div *ngIf=\"filtersForm.length > 1\" class=\"ml-auto flex-shrink-0\">\r\n <button\r\n (click)=\"removeFilter(i)\"\r\n class=\"flex h-10 w-10 items-center justify-center rounded-full transition-colors duration-300 hover:bg-red-100\"\r\n matTooltip=\"Remover filtro\"\r\n >\r\n <i class=\"fa fa-trash text-red-500 hover:text-red-600\"></i>\r\n </button>\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <!-- PANEL FOOTER: Add Filter & Actions -->\r\n <div\r\n class=\"-mb-2 flex flex-col items-center justify-between gap-4 border-t border-gray-200 pt-4 sm:flex-row\"\r\n >\r\n <!-- Add Filter Button -->\r\n <div *ngIf=\"dropdownItems.length > 0\">\r\n <button\r\n (click)=\"addFilter()\"\r\n class=\"transform rounded-full border-2 border-blue-300 bg-blue-50 px-6 py-2 text-sm font-medium text-blue-600 transition-all duration-300 hover:-translate-y-0.5 hover:border-blue-400 hover:bg-blue-100 hover:shadow-md\"\r\n matTooltip=\"Adicionar novo filtro\"\r\n >\r\n <i class=\"fa fa-plus mr-2\"></i>\r\n Adicionar Filtro\r\n </button>\r\n </div>\r\n\r\n <!-- Action Buttons -->\r\n <div class=\"flex flex-wrap gap-3\">\r\n <button\r\n (click)=\"search()\"\r\n type=\"button\"\r\n class=\"flex items-center gap-2 rounded-lg bg-green-600 px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-green-700\"\r\n matTooltip=\"Aplicar filtros\"\r\n >\r\n <i class=\"fa fa-search\"></i>\r\n Aplicar\r\n </button>\r\n\r\n <button\r\n (click)=\"resetFilter()\"\r\n class=\"flex items-center gap-2 rounded-lg bg-red-500 px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-red-600\"\r\n matTooltip=\"Limpar filtros\"\r\n >\r\n <i class=\"fas fa-redo-alt\"></i>\r\n Resetar\r\n </button>\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <div class=\"flex flex-col\">\r\n <div\r\n class=\"mx-auto flex flex-col\"\r\n *ngIf=\"data.tabs && data.tabs.tabsData && data.tabs.tabsData.length > 0\"\r\n >\r\n <!-- Calcular quantos grupos de 6 tabs existem -->\r\n <ng-container\r\n *ngFor=\"\r\n let groupIndex of getTabGroups(data.tabs.tabsData);\r\n let i = index\r\n \"\r\n >\r\n <div class=\"mx-auto flex flex-row\">\r\n <ng-container\r\n *ngFor=\"\r\n let tab of getTabGroup(data.tabs.tabsData, groupIndex);\r\n let j = index\r\n \"\r\n >\r\n <button\r\n class=\"border-2 border-gray-300 bg-gray-200 px-4 py-2 font-medium transition hover:brightness-95\"\r\n [ngClass]=\"\r\n isTabSelected(getRealTabIndex(i, j))\r\n ? 'border-b-0 brightness-110'\r\n : ''\r\n \"\r\n (click)=\"onTableSelected(i, j)\"\r\n >\r\n {{ tab.label }}\r\n <span\r\n *ngIf=\"tab.counter !== undefined\"\r\n class=\"ml-2 text-xs font-bold\"\r\n [ngClass]=\"tab.counterClass\"\r\n >\r\n {{ tab.counter }}\r\n </span>\r\n </button>\r\n </ng-container>\r\n </div>\r\n </ng-container>\r\n </div>\r\n <div class=\"mat-elevation-z8 w-full overflow-x-auto rounded-xl\">\r\n <table\r\n mat-table\r\n [dataSource]=\"dataSource\"\r\n matSort\r\n #sort=\"matSort\"\r\n matSortActive=\"createdAt\"\r\n matSortDirection=\"desc\"\r\n >\r\n <ng-container\r\n *ngFor=\"let col of data.displayedColumns\"\r\n matColumnDef=\"{{ col.property }}\"\r\n >\r\n <ng-container *matHeaderCellDef>\r\n <!-- IF THE COLUMN IS NOT SORTABLE, THEN DON'T SHOW THE SORT BUTTONS -->\r\n <th\r\n *ngIf=\"!col.isSortable || data.pagination === true\"\r\n mat-header-cell\r\n [ngClass]=\"\r\n (data.color?.bg ? ' ' + $any(data.color).bg : '') +\r\n (data.color?.text ? ' ' + $any(data.color).text : '')\r\n \"\r\n >\r\n {{ col.title }}\r\n </th>\r\n <!-- IF THE COLUMN IS SORTABLE, THEN SHOW THE SORT BUTTONS -->\r\n <th\r\n *ngIf=\"col.isSortable && data.pagination === false\"\r\n mat-header-cell\r\n mat-sort-header\r\n [ngClass]=\"\r\n (data.color?.bg ? ' ' + $any(data.color).bg : '') +\r\n (data.color?.text ? ' ' + $any(data.color).text : '')\r\n \"\r\n >\r\n {{ col.title }}\r\n </th>\r\n <td\r\n mat-cell\r\n *matCellDef=\"let row\"\r\n (click)=\"col.method ? col.method(row) : null\"\r\n (mouseenter)=\"onCellMouseEnter($event, row, col)\"\r\n (mouseleave)=\"onCellMouseLeave()\"\r\n (mousemove)=\"onCellMouseMove($event)\"\r\n >\r\n <!-- CHECK IF THE COLUMN MUST BE DISPLAYED -->\r\n <span *ngIf=\"!col.image && !col.iconClass && !col.method\">\r\n <ng-container>\r\n <span\r\n *ngIf=\"\r\n col.charLimit &&\r\n row[col.property] &&\r\n row[col.property].length > col.charLimit;\r\n else withinLimit\r\n \"\r\n >\r\n <a\r\n *ngIf=\"col.hasLink === true\"\r\n [href]=\"row[col.property]\"\r\n target=\"_blank\"\r\n >\r\n {{ getDisplayValue(col, row) }}\r\n </a>\r\n <a\r\n *ngIf=\"col.hasLink && isString(col.hasLink)\"\r\n [href]=\"col.hasLink\"\r\n target=\"_blank\"\r\n >\r\n {{ getDisplayValue(col, row) }}\r\n </a>\r\n <span\r\n *ngIf=\"col.hasLink !== true && !isString(col.hasLink)\"\r\n >\r\n {{ getDisplayValue(col, row) }}\r\n </span>\r\n </span>\r\n </ng-container>\r\n <ng-template #withinLimit>\r\n <a\r\n *ngIf=\"col.hasLink === true\"\r\n [href]=\"row[col.property]\"\r\n target=\"_blank\"\r\n >\r\n {{ getDisplayValue(col, row, true) }}\r\n </a>\r\n <a\r\n *ngIf=\"col.hasLink && isString(col.hasLink)\"\r\n [href]=\"col.hasLink\"\r\n target=\"_blank\"\r\n >\r\n {{ getDisplayValue(col, row, true) }}\r\n </a>\r\n <span\r\n *ngIf=\"col.hasLink !== true && !isString(col.hasLink)\"\r\n >\r\n {{ getDisplayValue(col, row, true) }}\r\n </span>\r\n </ng-template>\r\n </span>\r\n <!------------------- IMAGE ------------------>\r\n <img\r\n *ngIf=\"\r\n col.image && col.image.path && !col.iconClass && !col.method\r\n \"\r\n [src]=\"col.image.path + '/' + row[col.property]\"\r\n [ngClass]=\"col.image.class\"\r\n alt=\"Imagem\"\r\n />\r\n <img\r\n *ngIf=\"\r\n col.image && col.image.url && !col.iconClass && !col.method\r\n \"\r\n [src]=\"row[col.property]\"\r\n [ngClass]=\"col.image.class\"\r\n alt=\"Imagem\"\r\n />\r\n <ng-container *ngIf=\"col.iconClass\">\r\n <button\r\n *ngFor=\"let iconClass of col.iconClass\"\r\n (click)=\"\r\n iconClass.buttonMethod\r\n ? iconClass.buttonMethod(row, $event)\r\n : $event.stopPropagation()\r\n \"\r\n >\r\n <span\r\n [ngClass]=\"iconClass.class\"\r\n *ngIf=\"\r\n iconClass.condition === undefined ||\r\n (iconClass.condition !== undefined &&\r\n $any(iconClass.condition)(row))\r\n \"\r\n >{{ iconClass.text }}</span\r\n >\r\n </button>\r\n </ng-container>\r\n </td>\r\n </ng-container>\r\n </ng-container>\r\n\r\n <tr mat-header-row *matHeaderRowDef=\"columnProperties\"></tr>\r\n <tr\r\n [ngClass]=\"{\r\n 'example-element-row': data.isNotClickable === true,\r\n 'example-element-row cursor-pointer': !data.isNotClickable\r\n }\"\r\n mat-row\r\n *matRowDef=\"let row; columns: columnProperties\"\r\n (click)=\"goToDetails(row)\"\r\n ></tr>\r\n\r\n <!-- ROW SHOWN WHEN THERE IS NO MATCHING DATA. -->\r\n <tr class=\"mat-row\" *matNoDataRow>\r\n <td *ngIf=\"!isLoading\" class=\"mat-cell p-4\" colspan=\"4\">\r\n Nenhum resultado encontrado para a busca\r\n </td>\r\n </tr>\r\n </table>\r\n\r\n <div class=\"flex justify-center\" *ngIf=\"isLoading\">\r\n <mat-spinner></mat-spinner>\r\n </div>\r\n\r\n <div class=\"paginator-container\">\r\n <mat-paginator\r\n #paginator\r\n [pageSizeOptions]=\"[25, 50, 100]\"\r\n [pageSize]=\"pageSize\"\r\n [length]=\"totalItems\"\r\n showFirstLastButtons\r\n aria-label=\"Select page of periodic elements\"\r\n (page)=\"onPageChange($event)\"\r\n [ngClass]=\"{\r\n 'hide-length':\r\n ['filter', 'filterByDate', 'equals'].includes(\r\n this.currentArrange\r\n ) || this.data.filterFn,\r\n 'hide-next-button': !hasNextPage && data.pagination === true,\r\n 'hide-last-button':\r\n (!hasNextPage && data.pagination === true) || this.data.filterFn\r\n }\"\r\n >\r\n </mat-paginator>\r\n <div\r\n *ngIf=\"\r\n !isLoading &&\r\n dataSource?.data &&\r\n dataSource.data.length > 0 &&\r\n data?.filterFn\r\n \"\r\n class=\"page-number-display\"\r\n >\r\n {{ currentPageNumber }}\r\n </div>\r\n </div>\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <!-- TOOLTIP PERSONALIZADO -->\r\n <div\r\n *ngIf=\"showTooltip\"\r\n class=\"fixed z-50 max-w-md break-words rounded-lg bg-gray-800 px-3 py-2 text-sm text-white shadow-lg\"\r\n [style.left.px]=\"tooltipPosition.x\"\r\n [style.top.px]=\"tooltipPosition.y\"\r\n [style.pointer-events]=\"'none'\"\r\n >\r\n {{ tooltipContent }}\r\n </div>\r\n</div>\r\n", styles: ["::ng-deep .hide-length .mat-mdc-paginator-range-label{display:none}::ng-deep .hide-next-button .mat-mdc-tooltip-trigger.mat-mdc-paginator-navigation-next.mdc-icon-button.mat-mdc-icon-button.mat-unthemed.mat-mdc-button-base{visibility:hidden}::ng-deep .hide-next-button .mat-mdc-tooltip-trigger.mat-mdc-paginator-navigation-last.mdc-icon-button.mat-mdc-icon-button.mat-unthemed.mat-mdc-button-base.ng-star-inserted{visibility:hidden}::ng-deep .mat-mdc-text-field-wrapper.mdc-text-field.ng-tns-c162-1.mdc-text-field--filled{width:25dvw}::ng-deep .custom-filter .mat-mdc-text-field-wrapper{width:20dvw;max-width:300px}\n"] }]
2023
+ }], ctorParameters: function () { return [{ type: i1$1.Router }, { type: TableService }, { type: i1.AngularFirestore }]; }, propDecorators: { data: [{
2024
+ type: Input
2025
+ }], downloadTable: [{
2026
+ type: Input
2027
+ }], paginator: [{
2028
+ type: ViewChild,
2029
+ args: [MatPaginator]
2030
+ }], sort: [{
2031
+ type: ViewChild,
2032
+ args: [MatSort]
1931
2033
  }] } });
1932
2034
 
1933
- class NgFirebaseTableKxpModule {
1934
- }
1935
- NgFirebaseTableKxpModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgFirebaseTableKxpModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
1936
- NgFirebaseTableKxpModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.2.10", ngImport: i0, type: NgFirebaseTableKxpModule, declarations: [NgFirebaseTableKxpComponent, TableComponent], imports: [CommonModule,
1937
- ReactiveFormsModule,
1938
- FormsModule,
1939
- RouterModule,
1940
- MatTableModule,
1941
- MatPaginatorModule,
1942
- MatSortModule,
1943
- MatFormFieldModule,
1944
- MatInputModule,
1945
- MatSelectModule,
1946
- MatTooltipModule,
1947
- MatProgressSpinnerModule,
1948
- MatIconModule,
1949
- MatDialogModule,
1950
- NgxMaskDirective,
1951
- NgxMaskPipe], exports: [NgFirebaseTableKxpComponent, TableComponent] });
1952
- NgFirebaseTableKxpModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgFirebaseTableKxpModule, providers: [provideNgxMask()], imports: [CommonModule,
1953
- ReactiveFormsModule,
1954
- FormsModule,
1955
- RouterModule,
1956
- MatTableModule,
1957
- MatPaginatorModule,
1958
- MatSortModule,
1959
- MatFormFieldModule,
1960
- MatInputModule,
1961
- MatSelectModule,
1962
- MatTooltipModule,
1963
- MatProgressSpinnerModule,
1964
- MatIconModule,
1965
- MatDialogModule] });
1966
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgFirebaseTableKxpModule, decorators: [{
1967
- type: NgModule,
1968
- args: [{
1969
- declarations: [NgFirebaseTableKxpComponent, TableComponent],
1970
- imports: [
1971
- CommonModule,
1972
- ReactiveFormsModule,
1973
- FormsModule,
1974
- RouterModule,
1975
- MatTableModule,
1976
- MatPaginatorModule,
1977
- MatSortModule,
1978
- MatFormFieldModule,
1979
- MatInputModule,
1980
- MatSelectModule,
1981
- MatTooltipModule,
1982
- MatProgressSpinnerModule,
1983
- MatIconModule,
1984
- MatDialogModule,
1985
- NgxMaskDirective,
1986
- NgxMaskPipe,
1987
- ],
1988
- exports: [NgFirebaseTableKxpComponent, TableComponent],
1989
- providers: [provideNgxMask()],
1990
- }]
2035
+ class NgFirebaseTableKxpModule {
2036
+ }
2037
+ NgFirebaseTableKxpModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgFirebaseTableKxpModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
2038
+ NgFirebaseTableKxpModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.2.10", ngImport: i0, type: NgFirebaseTableKxpModule, declarations: [NgFirebaseTableKxpComponent, TableComponent], imports: [CommonModule,
2039
+ ReactiveFormsModule,
2040
+ FormsModule,
2041
+ RouterModule,
2042
+ MatTableModule,
2043
+ MatPaginatorModule,
2044
+ MatSortModule,
2045
+ MatFormFieldModule,
2046
+ MatInputModule,
2047
+ MatSelectModule,
2048
+ MatTooltipModule,
2049
+ MatProgressSpinnerModule,
2050
+ MatIconModule,
2051
+ MatDialogModule,
2052
+ NgxMaskDirective,
2053
+ NgxMaskPipe], exports: [NgFirebaseTableKxpComponent, TableComponent] });
2054
+ NgFirebaseTableKxpModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgFirebaseTableKxpModule, providers: [provideNgxMask()], imports: [CommonModule,
2055
+ ReactiveFormsModule,
2056
+ FormsModule,
2057
+ RouterModule,
2058
+ MatTableModule,
2059
+ MatPaginatorModule,
2060
+ MatSortModule,
2061
+ MatFormFieldModule,
2062
+ MatInputModule,
2063
+ MatSelectModule,
2064
+ MatTooltipModule,
2065
+ MatProgressSpinnerModule,
2066
+ MatIconModule,
2067
+ MatDialogModule] });
2068
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgFirebaseTableKxpModule, decorators: [{
2069
+ type: NgModule,
2070
+ args: [{
2071
+ declarations: [NgFirebaseTableKxpComponent, TableComponent],
2072
+ imports: [
2073
+ CommonModule,
2074
+ ReactiveFormsModule,
2075
+ FormsModule,
2076
+ RouterModule,
2077
+ MatTableModule,
2078
+ MatPaginatorModule,
2079
+ MatSortModule,
2080
+ MatFormFieldModule,
2081
+ MatInputModule,
2082
+ MatSelectModule,
2083
+ MatTooltipModule,
2084
+ MatProgressSpinnerModule,
2085
+ MatIconModule,
2086
+ MatDialogModule,
2087
+ NgxMaskDirective,
2088
+ NgxMaskPipe,
2089
+ ],
2090
+ exports: [NgFirebaseTableKxpComponent, TableComponent],
2091
+ providers: [provideNgxMask()],
2092
+ }]
1991
2093
  }] });
1992
2094
 
1993
- class NgFirebaseTableKxpService {
1994
- constructor() { }
1995
- }
1996
- NgFirebaseTableKxpService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgFirebaseTableKxpService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1997
- NgFirebaseTableKxpService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgFirebaseTableKxpService, providedIn: 'root' });
1998
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgFirebaseTableKxpService, decorators: [{
1999
- type: Injectable,
2000
- args: [{
2001
- providedIn: 'root',
2002
- }]
2095
+ class NgFirebaseTableKxpService {
2096
+ constructor() { }
2097
+ }
2098
+ NgFirebaseTableKxpService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgFirebaseTableKxpService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
2099
+ NgFirebaseTableKxpService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgFirebaseTableKxpService, providedIn: 'root' });
2100
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgFirebaseTableKxpService, decorators: [{
2101
+ type: Injectable,
2102
+ args: [{
2103
+ providedIn: 'root',
2104
+ }]
2003
2105
  }], ctorParameters: function () { return []; } });
2004
2106
 
2005
- /*
2006
- * Public API Surface of ng-firebase-table-kxp
2007
- */
2107
+ /*
2108
+ * Public API Surface of ng-firebase-table-kxp
2109
+ */
2008
2110
  // Main module
2009
2111
 
2010
- /**
2011
- * Generated bundle index. Do not edit.
2112
+ /**
2113
+ * Generated bundle index. Do not edit.
2012
2114
  */
2013
2115
 
2014
2116
  export { NgFirebaseTableKxpComponent, NgFirebaseTableKxpModule, NgFirebaseTableKxpService, TableComponent, TableService };