Skip to content

Commit 1cacc4d

Browse files
jhonyeduardojhosefmarks
authored andcommitted
feat(lookup): inclui coluna de ordenação na chamada do serviço
Inclui a coluna ordernada na chamada, via URL ou repassa por parâmetro caso utilizar serviço. Também deprecia o método getFilteredData e cria novo método getFilteredItems. Fixes DTHFUI-1742
1 parent d5ae905 commit 1cacc4d

19 files changed

+273
-78
lines changed

projects/ui/src/lib/components/po-field/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ export * from './po-input/po-input.component';
1515
export * from './po-login/po-login.component';
1616
export * from './po-lookup/interfaces/po-lookup-column.interface';
1717
export * from './po-lookup/interfaces/po-lookup-filter.interface';
18+
export * from './po-lookup/interfaces/po-lookup-filtered-items-params.interface';
1819
export * from './po-lookup/interfaces/po-lookup-literals.interface';
1920
export * from './po-lookup/interfaces/po-lookup-response-api.interface';
2021
export * from './po-lookup/po-lookup.component';

projects/ui/src/lib/components/po-field/po-lookup/interfaces/po-lookup-filter.interface.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { Observable } from 'rxjs';
22

3+
import { PoLookupFilteredItemsParams } from './po-lookup-filtered-items-params.interface';
34
import { PoLookupResponseApi } from './po-lookup-response-api.interface';
45

56
/**
@@ -12,19 +13,36 @@ import { PoLookupResponseApi } from './po-lookup-response-api.interface';
1213
export interface PoLookupFilter {
1314

1415
/**
16+
* **Deprecated**
17+
*
1518
* Método responsável por enviar um filtro para o serviço e receber os dados.
1619
*
1720
* Os parâmetros page e pageSize seguem o guia de implementação das APIs TOTVS, são utilizados para controlar a busca dos dados em cada
1821
* requisição do botão 'Carregar mais resultados'.
1922
*
2023
* Este método deve retornar um *Observable* com a resposta da API no formato da interface `PoLookupResponseApi`.
2124
*
25+
* > Este método está depreciado, deve-se utilizar a método `getFilteredItems`.
26+
*
2227
* @param {any} filter Utilizado pelo serviço para filtrar os dados.
2328
* @param {number} page Controla a paginação dos dados e recebe valor automaticamente a cada clique no botão 'Carregar mais resultados'.
2429
* @param {number} pageSize Quantidade de itens retornados cada vez que o serviço é chamado, por padrão é 10.
2530
* @param {any} filterParams Valor informado através da propriedade `p-filter-params`.
31+
*
32+
* @deprecated 4.x.x
33+
*
34+
*/
35+
getFilteredData?(filter: any, page: number, pageSize?: number, filterParams?: any): Observable<PoLookupResponseApi>;
36+
37+
/**
38+
* Método que será disparado ao filtrar a lista de itens ou carregar mais resultados no componente, deve-se retornar
39+
* um *Observable* com a resposta da API no formato da interface `PoLookupResponseApi`.
40+
*
41+
* > Esta propriedade será priorizada se houver também o método `getFilteredData`.
42+
*
43+
* @param {PoLookupFilteredItemsParams} params Objeto enviado por parâmetro que implementa a interface `PoLookupFilteredItemsParams`.
2644
*/
27-
getFilteredData(filter: any, page: number, pageSize?: number, filterParams?: any): Observable<PoLookupResponseApi>;
45+
getFilteredItems?(params: PoLookupFilteredItemsParams): Observable<PoLookupResponseApi>;
2846

2947
/**
3048
* Método responsável por enviar um valor que será buscado no serviço.
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* @usedBy PoLookupComponent
3+
*
4+
* @description
5+
*
6+
* Interface do objeto enviado como parâmetro na função `getFilteredItems`.
7+
*/
8+
export interface PoLookupFilteredItemsParams {
9+
10+
/**
11+
* Conteúdo utilizado para filtrar a lista de itens.
12+
*/
13+
filter?: string;
14+
15+
/**
16+
* Controla a paginação dos dados e recebe valor automaticamente a cada clique no botão 'Carregar mais resultados'.
17+
*/
18+
page?: number;
19+
20+
/**
21+
* Quantidade de itens retornados cada vez que o serviço é chamado, por padrão é 10.
22+
*/
23+
pageSize?: number;
24+
25+
/**
26+
* Valor informado através da propriedade `p-filter-params`.
27+
*/
28+
filterParams?: any;
29+
30+
/**
31+
* Coluna que está sendo ordenada na tabela.
32+
*
33+
* - Coluna decrescente será informada da seguinte forma: `-<colunaOrdenada>`, por exemplo `-name`.
34+
* - Coluna ascendente será informada da seguinte forma: `<colunaOrdenada>`, por exemplo `name`.
35+
*/
36+
order?: string;
37+
38+
}

projects/ui/src/lib/components/po-field/po-lookup/po-lookup-base.component.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,17 @@ export abstract class PoLookupBaseComponent implements ControlValueAccessor, OnD
150150
* url + ?page=1&pageSize=20&filter=Peter
151151
* ```
152152
*
153+
* Caso utilizar ordenação, a coluna ordenada será enviada através do parâmetro `order`, por exemplo:
154+
* - Coluna decrescente:
155+
* ```
156+
* url + ?page=1&pageSize=20&filter=Peter&order=-name
157+
* ```
158+
*
159+
* - Coluna ascendente:
160+
* ```
161+
* url + ?page=1&pageSize=20&filter=Peter&order=name
162+
* ```
163+
*
153164
* Se for definido a propriedade `p-filter-params`, o mesmo também será concatenado. Por exemplo, para o
154165
* parâmetro `{ age: 23 }` a URL ficaria:
155166
*

projects/ui/src/lib/components/po-field/po-lookup/po-lookup-modal/po-lookup-modal-base.component.spec.ts

Lines changed: 82 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import { Observable, of } from 'rxjs';
22

33
import * as UtilsFunctions from '../../../../utils/util';
44
import { expectPropertiesValues } from '../../../../util-test/util-expect.spec';
5+
import { PoTableColumnSort } from '../../../po-table/interfaces/po-table-column-sort.interface';
6+
import { PoTableColumnSortType } from '../../../po-table/enums/po-table-column-sort-type.enum';
57

68
import { poLookupLiteralsDefault, PoLookupModalBaseComponent } from './po-lookup-modal-base.component';
79

@@ -18,7 +20,7 @@ describe('PoLookupModalBaseComponent:', () => {
1820
component = new PoLookupModalComponent();
1921

2022
component.filterService = {
21-
getFilteredData: (searchValue, pageSize: number) => of({ items: [], hasNext: false }),
23+
getFilteredItems: ({filter, pageSize}) => of({ items: [], hasNext: false }),
2224
getObjectByValue: () => of()
2325
};
2426

@@ -34,11 +36,11 @@ describe('PoLookupModalBaseComponent:', () => {
3436
});
3537

3638
it('should init modal with items', () => {
37-
spyOn(component.filterService, 'getFilteredData').and.returnValue(of({ items: [].concat(items), hasNext : true }));
39+
spyOn(component.filterService, 'getFilteredItems').and.returnValue(of({ items: [].concat(items), hasNext : true }));
3840

3941
component.ngOnInit();
4042

41-
expect(component.filterService.getFilteredData).toHaveBeenCalled();
43+
expect(component.filterService.getFilteredItems).toHaveBeenCalled();
4244
expect(component.items.length).toBe(5);
4345
expect(component.hasNext).toBeTruthy();
4446
});
@@ -213,34 +215,59 @@ describe('PoLookupModalBaseComponent:', () => {
213215
expect(fakeSubscription.unsubscribe).not.toHaveBeenCalled();
214216
});
215217

216-
it('getFilteredData: shoud call `getFilteredData` and return a Observable.', () => {
218+
it('getFilteredItems: shoud call `getFilteredItems` and return a Observable if `getFilteredItems` is truthy', () => {
217219
const page = 1;
218220
const pageSize = 1;
219221
const filterParams = { code: 1 };
220-
const searchValue = 'po';
222+
const filter = 'po';
221223

222224
component.page = page;
223225
component.pageSize = pageSize;
224226
component.filterParams = filterParams;
225227

228+
spyOn(component.filterService, 'getFilteredItems').and.returnValue(of(<any> {items}));
229+
spyOn(component, <any> 'getFilteredParams').and.callThrough();
230+
231+
const filteredDataObservable = component['getFilteredItems'](filter);
232+
233+
expect(component['getFilteredParams']).toHaveBeenCalled();
234+
expect(filteredDataObservable instanceof Observable);
235+
expect(component.filterService.getFilteredItems).toHaveBeenCalledWith({filter, page, pageSize, filterParams});
236+
});
237+
238+
it('getFilteredItems: shoud call `getFilteredData` and return a Observable if `getFilteredItems` is falsy', () => {
239+
const page = 1;
240+
const pageSize = 1;
241+
const filterParams = { code: 1 };
242+
const filter = 'po';
243+
244+
component.page = page;
245+
component.pageSize = pageSize;
246+
component.filterParams = filterParams;
247+
248+
component.filterService.getFilteredItems = undefined;
249+
component.filterService.getFilteredData = () => of({ items: [], hasNext: false });
250+
226251
spyOn(component.filterService, 'getFilteredData').and.returnValue(of(<any> {items}));
252+
spyOn(component, <any> 'getFilteredParams');
227253

228-
const filteredDataObservable = component['getFilteredData'](searchValue);
254+
const filteredDataObservable = component['getFilteredItems'](filter);
229255

256+
expect(component['getFilteredParams']).not.toHaveBeenCalled();
230257
expect(filteredDataObservable instanceof Observable);
231-
expect(component.filterService.getFilteredData).toHaveBeenCalledWith(searchValue, page, pageSize, filterParams);
258+
expect(component.filterService.getFilteredData).toHaveBeenCalledWith(filter, page, pageSize, filterParams);
232259
});
233260

234-
it('search: should call `getFilteredData` if `searchValue` it`s truthy.', () => {
261+
it('search: should call `getFilteredItems` if `searchValue` it`s truthy.', () => {
235262
component.searchValue = 'Suco';
236263

237264
const filteredItems = items.filter(f => f.label.includes(component.searchValue));
238265

239-
spyOn(component, <any> 'getFilteredData').and.returnValue(of({ items: filteredItems, hasNext: true }));
266+
spyOn(component, <any> 'getFilteredItems').and.returnValue(of({ items: filteredItems, hasNext: true }));
240267

241268
component.search();
242269

243-
expect(component['getFilteredData']).toHaveBeenCalledWith('Suco');
270+
expect(component['getFilteredItems']).toHaveBeenCalledWith('Suco');
244271
expect(component.items.length).toBe(2);
245272
expect(component.hasNext).toBeTruthy();
246273
});
@@ -255,18 +282,18 @@ describe('PoLookupModalBaseComponent:', () => {
255282
expect(component['initializeData']).toHaveBeenCalled();
256283
});
257284

258-
it('showMoreEvent: should call `getFilteredData`, increment `page` and assign returned items to `items`.', () => {
285+
it('showMoreEvent: should call `getFilteredItems`, increment `page` and assign returned items to `items`.', () => {
259286
const searchValue = 'Chocolate';
260287
const returnedItems = [{ value: 6, label: 'Chocolate quente' }];
261288
component.page = 1;
262289
component.items = [].concat(items);
263290
component.searchValue = searchValue;
264291

265-
spyOn(component, <any> 'getFilteredData').and.returnValue(of({items: returnedItems }));
292+
spyOn(component, <any> 'getFilteredItems').and.returnValue(of({items: returnedItems }));
266293

267294
component.showMoreEvent();
268295

269-
expect(component['getFilteredData']).toHaveBeenCalledWith(searchValue);
296+
expect(component['getFilteredItems']).toHaveBeenCalledWith(searchValue);
270297
expect(component.items.length).toBe([...items, ...returnedItems].length);
271298
expect(component.page).toBe(2);
272299
expect(component.isLoading).toBeFalsy();
@@ -293,6 +320,48 @@ describe('PoLookupModalBaseComponent:', () => {
293320

294321
});
295322

323+
it('getFilteredParams: should return object with only truthy values', () => {
324+
const page = 1;
325+
const pageSize = 10;
326+
const filter = '';
327+
const expectedValue = { page, pageSize };
328+
329+
component.page = page;
330+
component.pageSize = pageSize;
331+
component.filterParams = undefined;
332+
component['sort'] = undefined;
333+
334+
const filteredParams = component['getFilteredParams'](filter);
335+
336+
expect(filteredParams).toEqual(expectedValue);
337+
});
338+
339+
it('getOrderParam: should return `column.property` of PoTableColumnSort object if PoTableColumnSortType is Ascending', () => {
340+
const sort: PoTableColumnSort = { column: { property: 'name' }, type: PoTableColumnSortType.Ascending };
341+
const expectedValue = 'name';
342+
343+
const orderParam = component['getOrderParam'](sort);
344+
345+
expect(orderParam).toBe(expectedValue);
346+
});
347+
348+
it('getOrderParam: should return `-column.property` of PoTableColumnSort object if PoTableColumnSortType is Descending', () => {
349+
const sort: PoTableColumnSort = { column: { property: 'name' }, type: PoTableColumnSortType.Descending };
350+
const expectedValue = '-name';
351+
352+
const orderParam = component['getOrderParam'](sort);
353+
354+
expect(orderParam).toBe(expectedValue);
355+
});
356+
357+
it('getOrderParam: should return undefined if PoTableColumnSort.column is undefined', () => {
358+
const expectedValue = undefined;
359+
360+
const orderParam = component['getOrderParam']();
361+
362+
expect(orderParam).toBe(expectedValue);
363+
});
364+
296365
});
297366

298367
});

projects/ui/src/lib/components/po-field/po-lookup/po-lookup-modal/po-lookup-modal-base.component.ts

Lines changed: 52 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,17 @@ import { EventEmitter, Input, OnDestroy, OnInit, Output, ViewChild } from '@angu
22

33
import { Observable , Subscription } from 'rxjs';
44
import { browserLanguage, isTypeof, poLocaleDefault } from '../../../../utils/util';
5+
import { PoModalAction } from '../../../../components/po-modal';
6+
import { PoModalComponent } from '../../../../components/po-modal/po-modal.component';
7+
import { PoTableColumnSort } from '../../../po-table/interfaces/po-table-column-sort.interface';
8+
import { PoTableColumnSortType } from '../../../po-table';
9+
import { poTableLiteralsDefault } from '../../../po-table/po-table-base.component';
510

611
import { PoLookupColumn } from '../interfaces/po-lookup-column.interface';
712
import { PoLookupFilter } from '../interfaces/po-lookup-filter.interface';
13+
import { PoLookupFilteredItemsParams } from '../interfaces/po-lookup-filtered-items-params.interface';
814
import { PoLookupLiterals } from '../interfaces/po-lookup-literals.interface';
915
import { PoLookupResponseApi } from '../interfaces/po-lookup-response-api.interface';
10-
import { PoModalAction } from '../../../../components/po-modal';
11-
import { PoModalComponent } from '../../../../components/po-modal/po-modal.component';
12-
import { poTableLiteralsDefault } from '../../../po-table/po-table-base.component';
1316

1417
export const poLookupLiteralsDefault = {
1518
en: <PoLookupLiterals> {
@@ -89,6 +92,8 @@ export abstract class PoLookupModalBaseComponent implements OnDestroy, OnInit {
8992
};
9093
tableLiterals: any;
9194

95+
protected sort: PoTableColumnSort;
96+
9297
private filterSubscription: Subscription;
9398
private searchSubscription: Subscription;
9499
private showMoreSubscription: Subscription;
@@ -168,7 +173,7 @@ export abstract class PoLookupModalBaseComponent implements OnDestroy, OnInit {
168173
this.page = 1;
169174
if (this.searchValue) {
170175
this.isLoading = true;
171-
this.searchSubscription = this.getFilteredData(this.searchValue).subscribe(data => {
176+
this.searchSubscription = this.getFilteredItems(this.searchValue).subscribe(data => {
172177
this.items = data.items;
173178
this.hasNext = data.hasNext;
174179
this.isLoading = false;
@@ -181,7 +186,7 @@ export abstract class PoLookupModalBaseComponent implements OnDestroy, OnInit {
181186
showMoreEvent() {
182187
this.page ++;
183188
this.isLoading = true;
184-
this.showMoreSubscription = this.getFilteredData(this.searchValue).subscribe(data => {
189+
this.showMoreSubscription = this.getFilteredItems(this.searchValue).subscribe(data => {
185190
data.items.forEach(item => {
186191
this.items.push(item);
187192
});
@@ -193,13 +198,52 @@ export abstract class PoLookupModalBaseComponent implements OnDestroy, OnInit {
193198
// Método responsável por abrir a modal de busca das informações.
194199
abstract openModal(): void;
195200

196-
private getFilteredData(searchValue): Observable<PoLookupResponseApi> {
197-
return this.filterService.getFilteredData(searchValue, this.page, this.pageSize, this.filterParams);
201+
private getFilteredItems(filter: string): Observable<PoLookupResponseApi> {
202+
const { page, pageSize, filterParams } = this;
203+
204+
if (this.filterService.getFilteredItems) {
205+
const filteredParams: PoLookupFilteredItemsParams = this.getFilteredParams(filter);
206+
207+
return this.filterService.getFilteredItems(filteredParams);
208+
}
209+
210+
return this.filterService.getFilteredData(filter, page, pageSize, filterParams);
211+
}
212+
213+
private getFilteredParams(filter: string) {
214+
const { page, pageSize, filterParams, sort } = this;
215+
216+
const filteredParams = {};
217+
const order = this.getOrderParam(sort);
218+
const params = { filter, page, pageSize, order, filterParams };
219+
220+
for (const key in params) {
221+
if (params.hasOwnProperty(key) && params[key]) {
222+
filteredParams[key] = params[key];
223+
}
224+
}
225+
226+
return filteredParams;
227+
}
228+
229+
private getOrderParam(sort: PoTableColumnSort = { type: undefined }) {
230+
const { column, type } = sort;
231+
232+
if (!column) {
233+
return;
234+
}
235+
236+
if (type === PoTableColumnSortType.Descending) {
237+
return `-${column.property}`;
238+
}
239+
240+
return `${column.property}`;
198241
}
199242

200243
private initializeData(): void {
201244
this.isLoading = true;
202-
this.filterSubscription = this.getFilteredData('').subscribe(data => {
245+
246+
this.filterSubscription = this.getFilteredItems('').subscribe(data => {
203247
this.items = data.items;
204248
this.hasNext = data.hasNext;
205249
this.isLoading = false;

projects/ui/src/lib/components/po-field/po-lookup/po-lookup-modal/po-lookup-modal.component.html

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@
4242
[p-literals]="tableLiterals"
4343
[p-loading]="isLoading"
4444
[p-show-more-disabled]="!hasNext"
45-
(p-show-more)="showMoreEvent()">
45+
(p-show-more)="showMoreEvent()"
46+
(p-sort-by)="sortBy($event)">
4647
</po-table>
4748

4849
</div>

0 commit comments

Comments
 (0)