ng-firebase-table-kxp 1.0.7 → 1.0.8

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