feat(employee-list): Added possibility to sort and paginate inside the list of employees (TV-217) (TV-222)

Squashed commit of the following:

commit f13b52a134693bb6237b2df6408020504c3fbe1c
Author: Erik Tiekstra <erik.tiekstra@arbetsformedlingen.se>
Date:   Wed Jun 9 07:47:56 2021 +0200

    Updated after PR

commit 4055d3a14eda9737ef76ed5e85ea35480e19e71c
Author: Erik Tiekstra <erik.tiekstra@arbetsformedlingen.se>
Date:   Mon Jun 7 15:20:26 2021 +0200

    updates after PR comments

commit f515ed6d06087f62de7522745691429d7ca91153
Author: Erik Tiekstra <erik.tiekstra@arbetsformedlingen.se>
Date:   Mon Jun 7 12:07:50 2021 +0200

    Now using Sort interface again

commit 5c793a5a7579a520c3792bb3d13c00bb68dbfcd4
Author: Erik Tiekstra <erik.tiekstra@arbetsformedlingen.se>
Date:   Mon Jun 7 11:54:27 2021 +0200

    Fixed bug showing wrong amount in pagination component

commit 7c55751147e05c1279b75356dc143b069e63e6b2
Merge: 11eab63 a701888
Author: Erik Tiekstra <erik.tiekstra@arbetsformedlingen.se>
Date:   Mon Jun 7 11:42:59 2021 +0200

    Updated after merge with develop

commit 11eab6330191a140c2cfd7094838495793e02719
Author: Erik Tiekstra <erik.tiekstra@arbetsformedlingen.se>
Date:   Mon Jun 7 11:23:52 2021 +0200

    Added functionality to sort on different columns

commit f13422a2aa53a69a243f32f9cd0b7ed6bd3441fc
Author: Erik Tiekstra <erik.tiekstra@arbetsformedlingen.se>
Date:   Fri Jun 4 11:40:22 2021 +0200

    Fixed other mappings after changes in the mock-api

commit ba2d3200167281422354f5e3cfdf7720444a9c4c
Merge: 6232b32 d91b3e6
Author: Erik Tiekstra <erik.tiekstra@arbetsformedlingen.se>
Date:   Fri Jun 4 10:00:00 2021 +0200

    Added paging functionality

commit 6232b3274ff73f2da929342a244fbc87430b796f
Author: Erik Tiekstra <erik.tiekstra@arbetsformedlingen.se>
Date:   Fri Jun 4 09:25:01 2021 +0200

    Added meta model and changed services to adapt new API data structure

commit 3ea0046bb713a6ee13d2a2cb2983e92d10559aa3
Author: Erik Tiekstra <erik.tiekstra@arbetsformedlingen.se>
Date:   Thu Jun 3 13:02:44 2021 +0200

    Adjusted mock-api functionality
This commit is contained in:
Erik Tiekstra
2021-06-09 07:51:22 +02:00
parent a70188863c
commit 48801a93a0
31 changed files with 392 additions and 173 deletions

View File

@@ -0,0 +1,4 @@
export enum SortOrder {
ASC = 'asc',
DESC = 'desc',
}

View File

@@ -6,11 +6,15 @@ export interface Authorization {
}
export interface AuthorizationApiResponse {
data: AuthorizationApiResponseData[];
}
export interface AuthorizationApiResponseData {
id: string;
name: AuthorizationEnum;
}
export function mapAuthorizationApiResponseToAuthorization(data: AuthorizationApiResponse): Authorization {
export function mapAuthorizationApiResponseToAuthorization(data: AuthorizationApiResponseData): Authorization {
const { id, name } = data;
return {
id,

View File

@@ -1,22 +1,43 @@
import { Authorization } from './authorization.model';
import { Authorization } from '@dafa-enums/authorization.enum';
import { Organization } from './organization.model';
import { Participant } from './participant.model';
import { PaginationMeta } from './pagination-meta.model';
import { Service } from './service.model';
import { User, UserApiResponse } from './user.model';
export interface Employee extends User {
languages: string[];
participants: Participant[];
export interface Employee {
id: string;
firstName: string;
lastName: string;
fullName: string;
ssn: string;
organizations: Organization[];
authorizations: Authorization[];
services: Service[];
}
export interface EmployeeApiResponse extends UserApiResponse {
languages: string[];
participants: Participant[];
export interface EmployeesApiResponse {
data: Employee[];
meta: PaginationMeta;
}
export interface EmployeesData {
data: Employee[];
meta: PaginationMeta;
}
export interface EmployeeApiResponse {
data: Employee;
}
export interface EmployeeApiResponseData {
id: string;
firstName: string;
lastName: string;
ssn: string;
organizations: Organization[];
authorizations: Authorization[];
services: Service[];
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface EmployeeApiRequestData {
firstName: string;
lastName: string;
@@ -38,8 +59,8 @@ export function mapEmployeeToEmployeeApiRequestData(data: Employee): EmployeeApi
};
}
export function mapEmployeeReponseToEmployee(data: EmployeeApiResponse): Employee {
const { id, firstName, lastName, ssn, services, languages, organizations, authorizations, participants } = data;
export function mapEmployeeReponseToEmployee(data: EmployeeApiResponseData): Employee {
const { id, firstName, lastName, ssn, services, organizations, authorizations } = data;
return {
id,
firstName,
@@ -48,8 +69,6 @@ export function mapEmployeeReponseToEmployee(data: EmployeeApiResponse): Employe
organizations,
authorizations,
services,
languages,
ssn,
participants,
};
}

View File

@@ -0,0 +1,6 @@
export interface PaginationMeta {
count: number;
limit: number;
page: number;
totalPages: number;
}

View File

@@ -1,7 +1,31 @@
import { ParticipantStatus } from '@dafa-enums/participant-status.enum';
import { Service } from '@dafa-enums/service.enum';
import { PaginationMeta } from './pagination-meta.model';
export interface Participant {
id: string;
firstName: string;
lastName: string;
fullName: string;
status: ParticipantStatus;
nextStep: string;
service: Service;
errandNumber: number;
startDate: Date;
endDate: Date;
handleBefore: Date;
}
export interface ParticipantsApiResponse {
data: ParticipantApiResponseData[];
meta?: PaginationMeta;
}
export interface ParticipantApiResponse {
data: ParticipantApiResponseData;
}
export interface ParticipantApiResponseData {
id: string;
firstName: string;
lastName: string;
@@ -12,5 +36,21 @@ export interface Participant {
startDate: Date;
endDate: Date;
handleBefore: Date;
fullName?: string;
}
export function mapParticipantApiResponseToParticipant(data: ParticipantApiResponseData): Participant {
const { id, firstName, lastName, status, nextStep, service, errandNumber, startDate, endDate, handleBefore } = data;
return {
id,
firstName,
lastName,
fullName: `${firstName} ${lastName}`,
status,
nextStep,
service,
errandNumber,
startDate,
endDate,
handleBefore,
};
}

View File

@@ -6,11 +6,15 @@ export interface Service {
}
export interface ServiceApiResponse {
data: ServiceApiResponseData[];
}
export interface ServiceApiResponseData {
id: string;
name: ServiceEnum;
}
export function mapServiceApiResponseToService(data: ServiceApiResponse): Service {
export function mapServiceApiResponseToService(data: ServiceApiResponseData): Service {
const { id, name } = data;
return {
id,

View File

@@ -1,7 +0,0 @@
import { Employee } from './employee.model';
import { Participant } from './participant.model';
export interface SortBy {
key: keyof Participant | keyof Employee;
reverse: boolean;
}

View File

@@ -0,0 +1,6 @@
import { SortOrder } from '@dafa-enums/sort-order.enum';
export interface Sort<Key> {
key: Key;
order: SortOrder;
}

View File

@@ -12,6 +12,10 @@ export interface User {
}
export interface UserApiResponse {
data: UserApiResponseData;
}
export interface UserApiResponseData {
id: string;
firstName: string;
lastName: string;
@@ -20,7 +24,7 @@ export interface UserApiResponse {
authorizations: Authorization[];
}
export function mapUserApiResponseToUser(data: UserApiResponse): User {
export function mapUserApiResponseToUser(data: UserApiResponseData): User {
const { id, firstName, lastName, ssn, organizations, authorizations } = data;
return {
id,

View File

@@ -8,6 +8,7 @@ export class CustomErrorHandler implements ErrorHandler {
handleError(error: any): void {
const customError: CustomError = errorToCustomError(error);
console.error(error);
this.errorService.add(customError);
}
}

View File

@@ -14,7 +14,7 @@ const routes: Routes = [
loadChildren: () => import('./pages/employees/employees.module').then(m => m.EmployeesModule),
},
{
path: 'personal/:id',
path: 'personal/:employeeId',
loadChildren: () => import('./pages/employee-card/employee-card.module').then(m => m.EmployeeCardModule),
},
{
@@ -22,7 +22,7 @@ const routes: Routes = [
loadChildren: () => import('./pages/employee-form/employee-form.module').then(m => m.EmployeeFormModule),
},
{
path: 'redigera-konto/:id',
path: 'redigera-konto/:employeeId',
loadChildren: () => import('./pages/employee-form/employee-form.module').then(m => m.EmployeeFormModule),
},
];

View File

@@ -1,10 +1,10 @@
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { UnsubscribeDirective } from '@dafa-directives/unsubscribe.directive';
import { Employee } from '@dafa-models/employee.model';
import { Participant } from '@dafa-models/participant.model';
import { EmployeeService } from '@dafa-services/api/employee.service';
import { BehaviorSubject, Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
@Component({
selector: 'dafa-employee-card',
@@ -12,20 +12,15 @@ import { BehaviorSubject, Observable } from 'rxjs';
styleUrls: ['./employee-card.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class EmployeeCardComponent extends UnsubscribeDirective {
detailedEmployeeData$: Observable<Employee>;
authorizationsAsString$: Observable<string>;
export class EmployeeCardComponent {
private _pendingSelectedParticipants$ = new BehaviorSubject<string[]>([]);
private _employeeId$: Observable<string> = this.activatedRoute.params.pipe(map(({ employeeId }) => employeeId));
authorizationsAsString$: Observable<string>;
detailedEmployeeData$: Observable<Employee> = this._employeeId$.pipe(
switchMap(employeeId => this.employeeService.fetchDetailedEmployeeData$(employeeId))
);
constructor(private activatedRoute: ActivatedRoute, private employeeService: EmployeeService) {
super();
super.unsubscribeOnDestroy(
this.activatedRoute.params.subscribe(({ id }) => {
this.detailedEmployeeData$ = this.employeeService.getDetailedEmployeeData(id);
})
);
}
constructor(private activatedRoute: ActivatedRoute, private employeeService: EmployeeService) {}
get pendingSelectedParticipants(): string[] {
return this._pendingSelectedParticipants$.getValue();

View File

@@ -6,27 +6,45 @@
<th scope="col" class="employees-list__column-head">
<button class="employees-list__sort-button" (click)="handleSort('fullName')">
Namn
<ng-container *ngIf="sortBy?.key === 'fullName'">
<digi-icon-caret-up class="employees-list__sort-icon" *ngIf="!sortBy.reverse"></digi-icon-caret-up>
<digi-icon-caret-down class="employees-list__sort-icon" *ngIf="sortBy.reverse"></digi-icon-caret-down>
<ng-container *ngIf="sort.key === 'fullName'">
<digi-icon-caret-up
class="employees-list__sort-icon"
*ngIf="sort.order === orderType.ASC"
></digi-icon-caret-up>
<digi-icon-caret-down
class="employees-list__sort-icon"
*ngIf="sort.order === orderType.DESC"
></digi-icon-caret-down>
</ng-container>
</button>
</th>
<th scope="col" class="employees-list__column-head">
<button class="employees-list__sort-button" (click)="handleSort('services')">
Tjänst
<ng-container *ngIf="sortBy?.key === 'services'">
<digi-icon-caret-up class="employees-list__sort-icon" *ngIf="!sortBy.reverse"></digi-icon-caret-up>
<digi-icon-caret-down class="employees-list__sort-icon" *ngIf="sortBy.reverse"></digi-icon-caret-down>
<ng-container *ngIf="sort.key === 'services'">
<digi-icon-caret-up
class="employees-list__sort-icon"
*ngIf="sort.order === orderType.ASC"
></digi-icon-caret-up>
<digi-icon-caret-down
class="employees-list__sort-icon"
*ngIf="sort.order === orderType.DESC"
></digi-icon-caret-down>
</ng-container>
</button>
</th>
<th scope="col" class="employees-list__column-head">
<button class="employees-list__sort-button" (click)="handleSort('organizations')">
Utförandeverksamheter
<ng-container *ngIf="sortBy?.key === 'organization'">
<digi-icon-caret-up class="employees-list__sort-icon" *ngIf="!sortBy.reverse"></digi-icon-caret-up>
<digi-icon-caret-down class="employees-list__sort-icon" *ngIf="sortBy.reverse"></digi-icon-caret-down>
<ng-container *ngIf="sort.key === 'organizations'">
<digi-icon-caret-up
class="employees-list__sort-icon"
*ngIf="sort.order === orderType.ASC"
></digi-icon-caret-up>
<digi-icon-caret-down
class="employees-list__sort-icon"
*ngIf="sort.order === orderType.DESC"
></digi-icon-caret-down>
</ng-container>
</button>
</th>
@@ -34,7 +52,7 @@
</tr>
</thead>
<tbody>
<tr *ngFor="let employee of pagedEmployees">
<tr *ngFor="let employee of employees">
<th scope="row">
<a [routerLink]="employee.id" class="employees-list__link">{{ employee.fullName }}</a>
</th>
@@ -64,8 +82,8 @@
[afTotalPages]="totalPages"
[afCurrentResultStart]="currentResultStart"
[afCurrentResultEnd]="currentResultEnd"
[afTotalResults]="employees.length"
(afOnPageChange)="handlePagination($event.detail)"
[afTotalResults]="count"
(afOnPageChange)="setNewPage($event.detail)"
af-result-name="medarbetare"
>
</digi-navigation-pagination>

View File

@@ -1,7 +1,8 @@
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { SortOrder } from '@dafa-enums/sort-order.enum';
import { Employee } from '@dafa-models/employee.model';
import { SortBy } from '@dafa-models/sort-by.model';
import { BehaviorSubject } from 'rxjs';
import { PaginationMeta } from '@dafa-models/pagination-meta.model';
import { Sort } from '@dafa-models/sort.model';
@Component({
selector: 'dafa-employees-list',
@@ -11,37 +12,36 @@ import { BehaviorSubject } from 'rxjs';
})
export class EmployeesListComponent {
@Input() employees: Employee[];
@Input() sortBy: SortBy | null;
@Input() meta: PaginationMeta;
@Input() sort: Sort<keyof Employee>;
@Input() order: SortOrder;
@Output() sorted = new EventEmitter<keyof Employee>();
@Output() paginated = new EventEmitter<number>();
private _currentPage$ = new BehaviorSubject<number>(1);
private _employeesPerPage = 10;
orderType = SortOrder;
get currentPage(): number {
return this._currentPage$.getValue();
return this.meta.page;
}
get totalPages(): number {
return Math.ceil(this.employees.length / this._employeesPerPage);
return this.meta?.totalPages;
}
get pagedEmployees(): Employee[] {
return [...this.employees].slice(this.currentResultStart - 1, this.currentResultEnd);
get count(): number {
return this.meta.count;
}
get currentResultStart(): number {
return (this.currentPage - 1) * this._employeesPerPage + 1;
return (this.currentPage - 1) * this.meta.limit + 1;
}
get currentResultEnd(): number {
return this.currentResultStart + this._employeesPerPage - 1;
const end = this.currentResultStart + this.meta.limit - 1;
return end < this.count ? end : this.count;
}
handleSort(key: keyof Employee): void {
this.sorted.emit(key);
}
handlePagination(page: number): void {
this._currentPage$.next(page);
setNewPage(page: number): void {
this.paginated.emit(page);
}
}

View File

@@ -22,10 +22,13 @@
</form>
<dafa-employees-list
*ngIf="filteredEmployees$ | async as employees; else loadingRef"
[employees]="employees"
[sortBy]="employeesSortBy$ | async"
*ngIf="employeesData$ | async as employeesData; else loadingRef"
[employees]="employeesData.data"
[meta]="employeesData.meta"
[sort]="sort$ | async"
[order]="order$ | async"
(sorted)="handleEmployeesSort($event)"
(paginated)="setNewPage($event)"
></dafa-employees-list>
</digi-typography>

View File

@@ -1,7 +1,7 @@
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { IconType } from '@dafa-enums/icon-type.enum';
import { Employee } from '@dafa-models/employee.model';
import { SortBy } from '@dafa-models/sort-by.model';
import { Employee, EmployeesData } from '@dafa-models/employee.model';
import { Sort } from '@dafa-models/sort.model';
import { EmployeeService } from '@dafa-services/api/employee.service';
import { BehaviorSubject, Observable } from 'rxjs';
@@ -13,8 +13,8 @@ import { BehaviorSubject, Observable } from 'rxjs';
})
export class EmployeesComponent {
private _searchValue$ = new BehaviorSubject<string>('');
filteredEmployees$: Observable<Employee[]> = this.employeeService.filteredEmployees$;
employeesSortBy$: Observable<SortBy | null> = this.employeeService.employeesSortBy$;
employeesData$: Observable<EmployeesData> = this.employeeService.employeesData$;
sort$: Observable<Sort<keyof Employee>> = this.employeeService.sort$;
iconType = IconType;
constructor(private employeeService: EmployeeService) {}
@@ -32,6 +32,10 @@ export class EmployeesComponent {
}
handleEmployeesSort(key: keyof Employee): void {
this.employeeService.setEmployeesSortKey(key);
this.employeeService.setSort(key);
}
setNewPage(page: number): void {
this.employeeService.setPage(page);
}
}

View File

@@ -6,8 +6,14 @@
<button class="participants-list__sort-button" (click)="handleSort('fullName')">
Namn
<ng-container *ngIf="sortBy?.key === 'fullName'">
<digi-icon-caret-up class="participants-list__sort-icon" *ngIf="!sortBy.reverse"></digi-icon-caret-up>
<digi-icon-caret-down class="participants-list__sort-icon" *ngIf="sortBy.reverse"></digi-icon-caret-down>
<digi-icon-caret-up
class="participants-list__sort-icon"
*ngIf="sortBy.order === 'asc'"
></digi-icon-caret-up>
<digi-icon-caret-down
class="participants-list__sort-icon"
*ngIf="sortBy.order === 'desc'"
></digi-icon-caret-down>
</ng-container>
</button>
</th>
@@ -15,8 +21,14 @@
<button class="participants-list__sort-button" (click)="handleSort('errandNumber')">
Ärendenummer
<ng-container *ngIf="sortBy?.key === 'errandNumber'">
<digi-icon-caret-up class="participants-list__sort-icon" *ngIf="!sortBy.reverse"></digi-icon-caret-up>
<digi-icon-caret-down class="participants-list__sort-icon" *ngIf="sortBy.reverse"></digi-icon-caret-down>
<digi-icon-caret-up
class="participants-list__sort-icon"
*ngIf="sortBy.order === 'asc'"
></digi-icon-caret-up>
<digi-icon-caret-down
class="participants-list__sort-icon"
*ngIf="sortBy.order === 'desc'"
></digi-icon-caret-down>
</ng-container>
</button>
</th>
@@ -24,8 +36,14 @@
<button class="participants-list__sort-button" (click)="handleSort('service')">
Tjänst
<ng-container *ngIf="sortBy?.key === 'service'">
<digi-icon-caret-up class="participants-list__sort-icon" *ngIf="!sortBy.reverse"></digi-icon-caret-up>
<digi-icon-caret-down class="participants-list__sort-icon" *ngIf="sortBy.reverse"></digi-icon-caret-down>
<digi-icon-caret-up
class="participants-list__sort-icon"
*ngIf="sortBy.order === 'asc'"
></digi-icon-caret-up>
<digi-icon-caret-down
class="participants-list__sort-icon"
*ngIf="sortBy.order === 'desc'"
></digi-icon-caret-down>
</ng-container>
</button>
</th>
@@ -33,8 +51,14 @@
<button class="participants-list__sort-button" (click)="handleSort('startDate')">
Startdatum
<ng-container *ngIf="sortBy?.key === 'startDate'">
<digi-icon-caret-up class="participants-list__sort-icon" *ngIf="!sortBy.reverse"></digi-icon-caret-up>
<digi-icon-caret-down class="participants-list__sort-icon" *ngIf="sortBy.reverse"></digi-icon-caret-down>
<digi-icon-caret-up
class="participants-list__sort-icon"
*ngIf="sortBy.order === 'asc'"
></digi-icon-caret-up>
<digi-icon-caret-down
class="participants-list__sort-icon"
*ngIf="sortBy.order === 'desc'"
></digi-icon-caret-down>
</ng-container>
</button>
</th>
@@ -42,8 +66,14 @@
<button class="participants-list__sort-button" (click)="handleSort('endDate')">
Slutdatum
<ng-container *ngIf="sortBy?.key === 'endDate'">
<digi-icon-caret-up class="participants-list__sort-icon" *ngIf="!sortBy.reverse"></digi-icon-caret-up>
<digi-icon-caret-down class="participants-list__sort-icon" *ngIf="sortBy.reverse"></digi-icon-caret-down>
<digi-icon-caret-up
class="participants-list__sort-icon"
*ngIf="sortBy.order === 'asc'"
></digi-icon-caret-up>
<digi-icon-caret-down
class="participants-list__sort-icon"
*ngIf="sortBy.order === 'desc'"
></digi-icon-caret-down>
</ng-container>
</button>
</th>
@@ -51,8 +81,14 @@
<button class="participants-list__sort-button" (click)="handleSort('handleBefore')">
Hantera innan
<ng-container *ngIf="sortBy?.key === 'handleBefore'">
<digi-icon-caret-up class="participants-list__sort-icon" *ngIf="!sortBy.reverse"></digi-icon-caret-up>
<digi-icon-caret-down class="participants-list__sort-icon" *ngIf="sortBy.reverse"></digi-icon-caret-down>
<digi-icon-caret-up
class="participants-list__sort-icon"
*ngIf="sortBy.order === 'asc'"
></digi-icon-caret-up>
<digi-icon-caret-down
class="participants-list__sort-icon"
*ngIf="sortBy.order === 'desc'"
></digi-icon-caret-down>
</ng-container>
</button>
</th>

View File

@@ -1,6 +1,6 @@
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { Participant } from '@dafa-models/participant.model';
import { SortBy } from '@dafa-models/sort-by.model';
import { Sort } from '@dafa-models/sort.model';
import { BehaviorSubject } from 'rxjs';
@Component({
@@ -11,7 +11,7 @@ import { BehaviorSubject } from 'rxjs';
})
export class ParticipantsListComponent {
@Input() participants: Participant[];
@Input() sortBy: SortBy | null;
@Input() sortBy: Sort<keyof Participant> | null;
@Output() sorted = new EventEmitter<keyof Participant>();
private _currentPage$ = new BehaviorSubject<number>(1);

View File

@@ -1,6 +1,6 @@
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Participant } from '@dafa-models/participant.model';
import { SortBy } from '@dafa-models/sort-by.model';
import { Sort } from '@dafa-models/sort.model';
import { ParticipantsService } from '@dafa-services/api/participants.service';
import { BehaviorSubject, Observable } from 'rxjs';
@@ -14,8 +14,10 @@ export class ParticipantsComponent {
private _searchValue$ = new BehaviorSubject<string>('');
activeParticipants$: Observable<Participant[]> = this.participantsService.activeParticipants$;
followUpParticipants$: Observable<Participant[]> = this.participantsService.followUpParticipants$;
activeParticipantsSortBy$: Observable<SortBy | null> = this.participantsService.activeParticipantsSortBy$;
followUpParticipantsSortBy$: Observable<SortBy | null> = this.participantsService.followUpParticipantsSortBy$;
activeParticipantsSortBy$: Observable<Sort<keyof Participant> | null> = this.participantsService
.activeParticipantsSortBy$;
followUpParticipantsSortBy$: Observable<Sort<keyof Participant> | null> = this.participantsService
.followUpParticipantsSortBy$;
constructor(private participantsService: ParticipantsService) {}

View File

@@ -17,8 +17,10 @@ const API_HEADERS = { headers: environment.api.headers };
export class AuthorizationService {
private _authorizationsApiUrl = `${environment.api.url}/authorizations`;
public authorizations$: Observable<Authorization[]> = this.httpClient
.get<AuthorizationApiResponse[]>(this._authorizationsApiUrl, API_HEADERS)
.pipe(map(response => response.map(authorization => mapAuthorizationApiResponseToAuthorization(authorization))));
.get<AuthorizationApiResponse>(this._authorizationsApiUrl, API_HEADERS)
.pipe(
map(response => response.data.map(authorization => mapAuthorizationApiResponseToAuthorization(authorization)))
);
constructor(private httpClient: HttpClient) {}
}

View File

@@ -1,79 +1,83 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ErrorType } from '@dafa-enums/error-type.enum';
import { SortOrder } from '@dafa-enums/sort-order.enum';
import { environment } from '@dafa-environment';
import {
Employee,
EmployeeApiResponse,
EmployeesApiResponse,
EmployeesData,
mapEmployeeReponseToEmployee,
mapEmployeeToEmployeeApiRequestData,
} from '@dafa-models/employee.model';
import { SortBy } from '@dafa-models/sort-by.model';
import { sort } from '@dafa-utils/sort.util';
import { Sort } from '@dafa-models/sort.model';
import { BehaviorSubject, combineLatest, Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
function filterEmployees(employees: Employee[], searchFilter: string): Employee[] {
return employees.filter(person => person.fullName.toLowerCase().includes(searchFilter.toLowerCase()));
}
import { catchError, map, switchMap } from 'rxjs/operators';
const API_HEADERS = { headers: environment.api.headers };
@Injectable({
providedIn: 'root',
})
export class EmployeeService {
private _employeeApiUrl = `${environment.api.url}/employee`;
private _employeesRawData: Observable<EmployeeApiResponse[]> = this.httpClient.get<EmployeeApiResponse[]>(
this._employeeApiUrl,
API_HEADERS
);
private _allEmployees$: Observable<Employee[]> = this._employeesRawData.pipe(
map(results => results.map(result => mapEmployeeReponseToEmployee(result)))
);
private _employeesSortBy$ = new BehaviorSubject<SortBy | null>({ key: 'fullName', reverse: false });
public employeesSortBy$: Observable<SortBy> = this._employeesSortBy$.asObservable();
private _apiUrl = `${environment.api.url}/employee`;
private _limit$ = new BehaviorSubject<number>(20);
private _page$ = new BehaviorSubject<number>(1);
private _sort$ = new BehaviorSubject<Sort<keyof Employee>>({ key: 'fullName', order: SortOrder.ASC });
public sort$: Observable<Sort<keyof Employee>> = this._sort$.asObservable();
private _searchFilter$ = new BehaviorSubject<string>('');
public searchFilter$: Observable<string> = this._searchFilter$.asObservable();
private _filteredEmployees$: Observable<Employee[]> = combineLatest([this._allEmployees$, this._searchFilter$]).pipe(
map(([employees, searchFilter]) => filterEmployees(employees, searchFilter))
private _fetchEmployees$(limit: number, page: number, sort: Sort<keyof Employee>): Observable<EmployeesData> {
return this.httpClient
.get<EmployeesApiResponse>(this._apiUrl, {
...API_HEADERS,
params: {
sort: sort.key,
order: sort.order,
limit: limit.toString(),
page: page.toString(),
},
})
.pipe(
map(({ data, meta }) => {
return { data: data.map(employee => mapEmployeeReponseToEmployee(employee)), meta };
})
);
}
public employeesData$: Observable<EmployeesData> = combineLatest([this._limit$, this._page$, this._sort$]).pipe(
switchMap(([limit, page, sort]) => this._fetchEmployees$(limit, page, sort))
);
public resultCount$: Observable<number> = this._employeesRawData.pipe(map(results => results.length)); // TODO: need META
public filteredEmployees$: Observable<Employee[]> = combineLatest([
this._filteredEmployees$,
this._employeesSortBy$,
]).pipe(
map(([employees, sortBy]) => {
return sortBy ? sort(employees, sortBy) : employees;
})
);
public fetchDetailedEmployeeData$(id: string): Observable<Employee> {
return this.httpClient
.get<EmployeeApiResponse>(`${this._apiUrl}/${id}`, { ...API_HEADERS })
.pipe(map(result => mapEmployeeReponseToEmployee(result.data)));
}
constructor(private httpClient: HttpClient) {}
public getDetailedEmployeeData(id: string): Observable<Employee> {
return this.httpClient
.get<EmployeeApiResponse>(`${this._employeeApiUrl}/${id}`, { ...API_HEADERS })
.pipe(map(result => mapEmployeeReponseToEmployee(result)));
}
public setSearchFilter(value: string) {
this._searchFilter$.next(value);
}
public setEmployeesSortKey(key: keyof Employee) {
const currentSortBy = this._employeesSortBy$.getValue();
const reverse = currentSortBy?.key === key ? !currentSortBy.reverse : false;
this._employeesSortBy$.next({ key, reverse });
public setSort(newSortKey: keyof Employee) {
const currentSort = this._sort$.getValue();
let order = currentSort.key === newSortKey && currentSort.order === SortOrder.ASC ? SortOrder.DESC : SortOrder.ASC;
this._sort$.next({ key: newSortKey, order });
}
public setPage(page: number) {
this._page$.next(page);
}
public postNewEmployee(employeeData: Employee): Observable<string> {
return this.httpClient
.post<any>(this._employeeApiUrl, mapEmployeeToEmployeeApiRequestData(employeeData), API_HEADERS)
.pipe(
map(({ id }) => id),
catchError(error => throwError({ message: error, type: ErrorType.API }))
);
return this.httpClient.post<any>(this._apiUrl, mapEmployeeToEmployeeApiRequestData(employeeData), API_HEADERS).pipe(
map(({ id }) => id),
catchError(error => throwError({ message: error, type: ErrorType.API }))
);
}
}

View File

@@ -1,9 +1,14 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ParticipantStatus } from '@dafa-enums/participant-status.enum';
import { SortOrder } from '@dafa-enums/sort-order.enum';
import { environment } from '@dafa-environment';
import { Participant } from '@dafa-models/participant.model';
import { SortBy } from '@dafa-models/sort-by.model';
import {
mapParticipantApiResponseToParticipant,
Participant,
ParticipantsApiResponse,
} from '@dafa-models/participant.model';
import { Sort } from '@dafa-models/sort.model';
import { sort } from '@dafa-utils/sort.util';
import { BehaviorSubject, combineLatest, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@@ -21,13 +26,23 @@ function filterParticipants(participants: Participant[], searchFilter: string):
providedIn: 'root',
})
export class ParticipantsService {
private _allParticipants$: Observable<Participant[]> = this.httpClient.get<Participant[]>(
`${environment.api.url}/participants`
);
private _activeParticipantsSortBy$ = new BehaviorSubject<SortBy | null>({ key: 'handleBefore', reverse: false });
public activeParticipantsSortBy$: Observable<SortBy> = this._activeParticipantsSortBy$.asObservable();
private _followUpParticipantsSortBy$ = new BehaviorSubject<SortBy | null>({ key: 'handleBefore', reverse: false });
public followUpParticipantsSortBy$: Observable<SortBy> = this._followUpParticipantsSortBy$.asObservable();
private _allParticipants$: Observable<Participant[]> = this.httpClient
.get<ParticipantsApiResponse>(`${environment.api.url}/participants`)
.pipe(map(response => response.data.map(participant => mapParticipantApiResponseToParticipant(participant))));
private _activeParticipantsSortBy$ = new BehaviorSubject<Sort<keyof Participant> | null>({
key: 'handleBefore',
order: SortOrder.ASC,
});
public activeParticipantsSortBy$: Observable<
Sort<keyof Participant>
> = this._activeParticipantsSortBy$.asObservable();
private _followUpParticipantsSortBy$ = new BehaviorSubject<Sort<keyof Participant> | null>({
key: 'handleBefore',
order: SortOrder.ASC,
});
public followUpParticipantsSortBy$: Observable<
Sort<keyof Participant>
> = this._followUpParticipantsSortBy$.asObservable();
private _searchFilter$ = new BehaviorSubject<string>('');
public searchFilter$: Observable<string> = this._searchFilter$.asObservable();
@@ -64,14 +79,20 @@ export class ParticipantsService {
public setActiveParticipantsSortKey(key: keyof Participant) {
const currentSortBy = this._activeParticipantsSortBy$.getValue();
const reverse = currentSortBy?.key === key ? !currentSortBy.reverse : false;
this._activeParticipantsSortBy$.next({ key, reverse });
let order = currentSortBy.order;
if (currentSortBy?.key === key) {
order = order === SortOrder.ASC ? SortOrder.DESC : SortOrder.ASC;
}
this._activeParticipantsSortBy$.next({ key, order });
}
public setFollowUpParticipantsSortKey(key: keyof Participant) {
const currentSortBy = this._followUpParticipantsSortBy$.getValue();
const reverse = currentSortBy?.key === key ? !currentSortBy.reverse : false;
this._followUpParticipantsSortBy$.next({ key, reverse });
let order = currentSortBy.order;
if (currentSortBy?.key === key) {
order = order === SortOrder.ASC ? SortOrder.DESC : SortOrder.ASC;
}
this._followUpParticipantsSortBy$.next({ key, order });
}
constructor(private httpClient: HttpClient) {}

View File

@@ -13,8 +13,8 @@ const API_HEADERS = { headers: environment.api.headers };
export class ServiceService {
private _servicesApiUrl = `${environment.api.url}/services`;
public services$: Observable<Service[]> = this.httpClient
.get<ServiceApiResponse[]>(this._servicesApiUrl, API_HEADERS)
.pipe(map(response => response.map(service => mapServiceApiResponseToService(service))));
.get<ServiceApiResponse>(this._servicesApiUrl, API_HEADERS)
.pipe(map(response => response.data.map(service => mapServiceApiResponseToService(service))));
constructor(private httpClient: HttpClient) {}
}

View File

@@ -14,7 +14,7 @@ export class UserService {
private _userApiUrl = `${environment.api.url}/currentUser`;
public currentUser$: Observable<User> = this.httpClient
.get<UserApiResponse>(this._userApiUrl, API_HEADERS)
.pipe(map(response => mapUserApiResponseToUser(response)));
.pipe(map(response => mapUserApiResponseToUser(response.data)));
constructor(private httpClient: HttpClient) {}
}

View File

@@ -21,7 +21,6 @@ export class ErrorService {
}
public add(error: CustomError) {
console.error(error);
this.errorQueue$.next([...this.errorQueue$.value, error]);
this.appRef.tick();
}

View File

@@ -1,11 +1,10 @@
import { SortBy } from '@dafa-models/sort-by.model';
import { Sort } from '@dafa-models/sort.model';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function sort(data: any[], sortBy: SortBy): any[] {
const reverse = sortBy.reverse ? -1 : 1;
export function sort<T>(data: T[], sort: Sort<keyof T>): T[] {
const reverse = sort.order === 'desc' ? -1 : 1;
return [...data].sort((a, b) => {
const first = a[sortBy.key];
const second = b[sortBy.key];
const first = a[sort.key];
const second = b[sort.key];
return reverse * (+(first > second) - +(second > first));
});

View File

@@ -4,7 +4,7 @@
"description": "A mock api implementing all needed endpoints for dafa-web",
"scripts": {
"generate-api": "node ./scripts/generate-api.js",
"start": "npm run generate-api && json-server --watch api.json --port 8000 --routes routes.json",
"start": "npm run generate-api && node server.js",
"start:delay": "npm start -- --delay 500"
},
"author": "Erik Tiekstra (erik.tiekstra@arbetsformedlingen.se)",

View File

@@ -1,7 +0,0 @@
{
"/api/*": "/$1",
"/participants": "/participants?_embed=employees",
"/participant/:id": "/participants/:id?_embed=employees",
"/employee": "/employees",
"/employee/:id": "/employees/:id"
}

View File

@@ -25,6 +25,7 @@ function generateEmployees(amount = 10) {
organizations: [ORGANIZATIONS[Math.floor(Math.random() * ORGANIZATIONS.length)]],
services: [SERVICES[Math.floor(Math.random() * SERVICES.length)]],
authorizations: authorizations.generate(),
createdAt: Date.now(),
};
employees.push(person);

View File

@@ -8,7 +8,7 @@ import organizations from './organizations.js';
import participants from './participants.js';
import services from './services.js';
const generatedEmployees = employees.generate(10);
const generatedEmployees = employees.generate(50);
const apiData = {
services: services.generate(),

View File

@@ -0,0 +1,61 @@
import jsonServer from 'json-server';
const server = jsonServer.create();
const router = jsonServer.router('api.json');
const middlewares = jsonServer.defaults();
server.use(middlewares);
server.use(
jsonServer.rewriter({
'/api/*': '/$1',
'*sort=services*': '$1sort=services[0].name$2',
'*sort=organizations*': '$1sort=organizations[0].address.city$2',
'*sort=fullName*': '$1sort=firstName,lastName$2',
'/employee*': '/employees$1',
'/participants': '/participants?_embed=employees',
'/participant/:id': '/participants/:id?_embed=employees',
'*page=*': '$1_page=$2',
'*limit=*': '$1_limit=$2',
'*sort=*': '$1_sort=$2',
'*order=*': '$1_order=$2',
})
);
router.render = (req, res) => {
const params = new URLSearchParams(req._parsedUrl.query);
// Add createdAt to the body
if (req.originalMethod === 'POST') {
req.body.createdAt = Date.now();
}
res.jsonp({
data: res.locals.data,
...appendMetaData(params, res),
});
};
server.use(router);
server.listen(8000, () => {
console.info('JSON Server is running');
});
function appendMetaData(params, res) {
if (params.has('_page')) {
const limit = +params.get('_limit');
const page = +params.get('_page');
const count = res.get('X-Total-Count');
const totalPages = Math.ceil(count / limit);
return {
meta: {
count,
limit,
page,
totalPages,
},
};
}
return null;
}