scieee AI-readable full text Open interactive document viewer

Aplicació web per a gestió de projectes

Vilella Muñoz, Marc

Abstract

The use of management applications has increased exponentially in recent years with the technological revolution. This fact led to have a wide variety of applications for this field; however, in most cases, each application has a very specific purpose requiring users to use several services. The project is an attempt to design and create entirely a web application to obtain an all-in-one manager. The software seeks to provide the necessary functionalities for the management and administration of projects in a single place, in other words, a greater simplicity of usage, which will lead to have a great benefit differentiating itself from other similar services. The web application is based on the use of the Angular framework that allows improving its scalability and performance with the adoption of best practices. In addition, it supports the implementation of a reactive state management that substantially improves graphic performance and simplifies application growth. On the other hand, the server is made with Node.js, which works in two modes, via HTTP requests for authentication and via WebSockets for the remaining functionalities, allowing simultaneity among clients and thus improve the user experience. Once the development has progressed, a set of functional tests ensures that the functionalities are working properly. These tests will be performed each time that there is a new functionality in the application in order to verify that the previous functionalities are still working. The document, in addition to the development and verification, includes the work plan with a Gantt diagram and the monthly hours per month, the design of the web application using views, structure of the database, the current final views and how the application will progress once submitted.

Full text

FINAL DEGREE PROJECT TFG TITLE: Application for Project Management DEGREE: Bachelor’s degree in Telecommunications Systems Engineering AUTHOR: Marc Vilella Muñoz ADVISOR: Miguel Valero García DATE: July 6, 2019 Title: Application for Project Management Author: Marc Vilella Muñoz Director: Miguel Valero García Date: July 6th 2019 Overview The use of management applications has increased exponentially in recent years with the technological revolution. This fact led to have a wide variety of applications for this field; however, in most cases, each application has a very specific purpose requiring users to use several services. The project is an attempt to design and create entirely a web application to obtain an all-in-one manager. The software seeks to provide the necessary functionalities for the management and administration of projects in a single place, in other words, a greater simplicity of usage, which will lead to have a great benefit differentiating itself from other similar services. The web application is based on the use of the Angular framework that allows improving its scalability and performance with the adoption of best practices. In addition, it supports the implementation of a reactive state management that substantially improves graphic performance and simplifies application growth. On the other hand, the server is made with Node.js, which works in two modes, via HTTP requests for authentication and via WebSockets for the remaining functionalities, allowing simultaneity among clients and thus improve the user experience. Once the development has progressed, a set of functional tests ensures that the functionalities are working properly. These tests will be performed each time that there is a new functionality in the application in order to verify that the previous functionalities are still working. The document, in addition to the development and verification, includes the work plan with a Gantt diagram and the monthly hours per month, the design of the web application using views, structure of the database, the current final views and how the application will progress once submitted. 4 Application for Project Management Títol: Aplicación para la admistración de proyectos Autor: Marc Vilella Muñoz Director: Miguel Valero García Data: 6 de julio del 2019 Resumen El uso de aplicaciones de gestión ha aumentado exponencialmente en los últimos años con la revolución tecnológica. Este hecho llevó a tener una gran variedad de aplicaciones para este campo; sin embargo, en la mayoría de casos, cada aplicación tiene un propósito muy específico que requiere que los usuarios utilicen varios servicios. El proyecto tiene el objetivo de diseñar y crear una aplicación web para obtener un gestor todo-en-uno. El software busca proporcionar las funcionalidades necesarias para la gestión y administración de proyectos en una sola herramienta, es decir, una mayor simplicidad de uso, lo que permitirá obtener un gran valor diferencial respecto otros servicios similares. La aplicación web se basa en la utilización del framework Angular que permite con el uso de buenas prácticas mejorar su escalabilidad y rendimiento. Además, permite el uso de una máquina de estados que mejora sustancialmente el rendimiento gráfico y facilita la expansión de la aplicación. Por otro lado, el servidor se realiza con Node.js, el cual funciona en dos modos, a través de peticiones HTTP para la autenticación y a través de WebSockets el resto de funcionalidades, lo que permite la simultaneidad entre clientes y así mejorar la experiencia de usuario. Una vez que el desarrollo progresa, un conjunto de pruebas funcionales asegura que la aplicación sigue funcionando correctamente. Estas pruebas se realizarán cada vez que haya una nueva funcionalidad en el proyeto para verificar que las funcionalidades anteriores siguen funcionando. El documento, además del desarrollo y verificación, incluye el plan de trabajo con un diagrama de Gantt y las horas mensuales dedicadas al proyecto, el diseño de la aplicación web utilizando un diagrama de vistas, la estructura de la base de datos, las vistas finales actuales y cómo progresará la aplicación una vez presentada. 6 Application for Project Management ÍNDEX INTRODUCTION ................................................................................................ 1 CHAPTER 1. BACKGROUND RESEARCH ...................................................... 2 1.1. Ideal application................................................................................................................. 2 1.2. Similar applications ........................................................................................................... 2 CHAPTER 2. PROJECT DESCRIPTION ........................................................... 4 2.1. Objectives ........................................................................................................................... 4 2.2. Functionalities ................................................................................................................... 4 2.3. Work plan ........................................................................................................................... 5 CHAPTER 3. TECHNOLOGIES ........................................................................ 6 3.1. Programming languages .................................................................................................. 6 3.1.1. TypeScript ............................................................................................................... 6 3.1.2. HTML5 .................................................................................................................... 6 3.1.3. SCSS ...................................................................................................................... 6 3.1.4. JavaScript ............................................................................................................... 6 3.1.5. MongoDB ................................................................................................................ 6 3.2. Development Environment ............................................................................................... 7 3.2.1. Visual Studio Code ................................................................................................. 7 3.2.2. Angular ................................................................................................................... 7 3.2.3. Node.js .................................................................................................................... 7 3.2.4. MongoDB Compass ............................................................................................... 7 3.3. Third-party codes .............................................................................................................. 8 3.3.1. Restify ..................................................................................................................... 8 3.3.2. Socket.IO ................................................................................................................ 8 3.3.3. NgRx ....................................................................................................................... 8 3.3.4. Angular Material ..................................................................................................... 8 CHAPTER 4. DESIGN ....................................................................................... 9 4.1. Overview ............................................................................................................................. 9 4.2. Server ................................................................................................................................ 10 4.3. Database architecture ..................................................................................................... 11 4.4. Client ................................................................................................................................. 13 4.5. Working prototype ........................................................................................................... 14 4.5.1. Navigation ............................................................................................................. 14 4.5.2. Templates ............................................................................................................. 15 4.5.3. Views .................................................................................................................... 16 8 Application for Project Management CHAPTER 5. DEVELOPMENT ........................................................................ 19 5.1. Front end .......................................................................................................................... 19 5.1.1. Root module ......................................................................................................... 19 5.1.2. Authentication module .......................................................................................... 20 5.1.3. Application module ............................................................................................... 21 5.1.4. Authentication service .......................................................................................... 23 5.1.5. Socket service ...................................................................................................... 24 5.1.6. Translate service .................................................................................................. 25 5.1.7. Directives .............................................................................................................. 26 5.1.8. Pipes ..................................................................................................................... 27 5.1.9. Reactive state management ................................................................................. 28 5.1.10. Error handling ....................................................................................................... 30 5.1.11. Board component ................................................................................................. 31 5.2. Back end ........................................................................................................................... 33 5.2.1. Server initialization ............................................................................................... 33 5.2.2. Routes .................................................................................................................. 34 5.2.3. Controllers ............................................................................................................ 36 5.2.4. Emails ................................................................................................................... 37 5.2.5. Sensible data ........................................................................................................ 39 5.2.6. Actions log ............................................................................................................ 40 5.2.7. Errors .................................................................................................................... 42 CHAPTER 6. TEST .......................................................................................... 44 6.1. Test ................................................................................................................................... 44 6.2. Results .............................................................................................................................. 45 CONCLUSIONS ............................................................................................... 49 FUTURE WORK .............................................................................................. 50 REFERENCES AND BIBLIOGRAPHY ............................................................ 51 LIST OF FIGURES Figure 1.1: Application comparison 3 Figure 2.1: Gantt diagram using TeamGantt [4] 5 Figure 2.2: Monthly hours graph 5 Figure 4.1: Design diagram 9 Figure 4.2. Node.js diagram 10 Figure 4.3: MongoDB database design 12 Figure 4.4: Angular diagram 13 Figure 4.5: Navigation diagram of log in view 14 Figure 4.6: Navigation diagram of dashboard view 14 Figure 4.7: Authentication and application templates, respectively 15 Figure 4.8: Authentication views: log in, password recovery and sign up 16 Figure 4.9: Dashboard and calendar views, respectively 16 Figure 4.10: Board views: Boards list, creator, board, settings and card 17 Figure 4.11: Project views: Projects list, project creator and project (3, 4 and 5) 18 Figure 4.12: Profile view 18 Figure 5.1: Root module configuration 19 Figure 5.2: Root routing configuration 20 Figure 5.3: Authentication module structure 20 Figure 5.4: Application module structure 22 Figure 5.5: Log in function 23 Figure 5.6: Log in function usage 23 Figure 5.7: Create socket connection 24 Figure 5.8: Emit and listen functions in socket service 24 Figure 5.9: Language file example 25 Figure 5.10: Getting translation in HTML 25 Figure 5.11: Getting translation in TypeScript 25 Figure 5.12: Click inside directive code 26 Figure 5.13: Numberpipe directive code 27 Figure 5.14: NgRx flow diagram 28 Figure 5.15: AddCardList action dispatcher 29 Figure 5.16: Effect AddCardList 29 Figure 5.17: Add Card List events 29 Figure 5.18: AddCardListSuccess reducer 30 Figure 5.19: Board.container.ts example 31 Figure 5.20: Board.container.html 32 Figure 5.21: Receiving objects and emitting events 32 Figure 5.22: Board view 32 Figure 5.23: Server initialization 33 Figure 5.24: Part of user routes 34 Figure 5.25: Part of board routes 35 Figure 5.26: HTTP request handling example 36 Figure 5.27: WebSocket event handling example 36 Figure 5.28: Nodemailer configuration 37 Figure 5.29: Send email function and email confirmation object 38 Figure 5.30: Hash plaintext example 39 Figure 5.31: Hash verification example 39 Figure 5.32: Logging sign up successful action 40 Figure 5.33: Actions log 40 Figure 5.34: Returning error in HTTP example 41 Figure 5.35: Custom error handling in WebSockets 41 Figure 5.36: Returning error in WebSockets example 42 Figure 6.1: Log in and sign up views, respectively 44 Figure 6.2: Registration and password request emails, respectively 44 Figure 6.3: Board creator overlay 45 Figure 6.4: Board selection 45 Figure 6.5: Board item 46 Figure 6.6: Task item overlay 47 Figure 6.7: Board settings: statistics and member management, respectively 47 4 Application for Project Management CHAPTER 2. PROJECT DESCRIPTION 2.1. Objectives The aim of the project is to create an application for project management, which the main function will allow the developer to control different pending tasks and the current state of each development as well as the time remaining before due date. In addition to this functionality, the application is the unification of different services to obtain an all-in-one manager. The integration of distinct characteristics associated with the direct development of the product will lead the application to have a great benefit differentiating itself from other similar services. Therefore, in order to have a real knowledge of the correct implementation of the different services, some testers will carry an examination and then, the feedback obtained will be used to release more accurate product to what the market needs. 2.2. Functionalities  Project manager: developers will have a system to have control of the development state of each task of the project and/or the tasks to which they belong.  Project administrator: it will be able to have real-time statistics of the development state of the project, the hours involved in each task and export the data.  Notification system: the application shall notify the relevant users when the tasks reach their deadline or when is indicated by the users.  Chat: internal chat in which users will be able to interact allowing a more effective collaboration  Developer portal: place where the developer can see a summary of his recent tasks, pending tasks and recommendations. Project description 5 2.3. Work plan The next two figures show how many hours approximately I spent in the project. The first image illustrates the project schedule, the devoted hours for each task and the current progress. Each colour has a different meaning, the green tasks are completed, the yellow tasks needs the completion of another tasks and red is the initial expected time; however, I do not have enough time to do it and is pending. The second bar chart shows the hours dedicated to the project every month. Figure 2.1. Gantt diagram using TeamGantt [4] Figure 2.2. Monthly hours graph 0 10 20 30 40 50 60 70 80 90 October NovemberDecember January February March April May June July Monthly Hours Completed Blocked Pending 6 Application for Project Management CHAPTER 3. TECHNOLOGIES 3.1. Programming languages 3.1.1. TypeScript It is a superset of JavaScript adding an optional static typing to the language. It is used in the client-side in order to create a dynamic and interactive web site. 3.1.2. HTML5 It defines the properties and behaviours of web page content by implementing a mark-up based pattern to it. It is used for views. 3.1.3. SCSS It is a pre-processor scripting language is interpreted into CSS. It allows creating variables and separating the styles from the HTML and sharing the same properties along views. Used to improve visual appearance. 3.1.4. JavaScript It is an object-oriented scripting language used in the in the server-side combined with Node.js. 3.1.5. MongoDB MongoDB is an open source and non-relational (NoSQL) database program that uses JSON-like documents. Technologies 7 3.2. Development Environment 3.2.1. Visual Studio Code It is a free open source development environment able to work with a large amount of programming languages and can be extended with multiple plug-ins. 3.2.2. Angular It is an open-source web application framework, based on TypeScript and uses HTML5 and SCSS. Angular builds native mobile and native desktop. The MVC framework aims for the best performance and scalability and allows the developer to build data models on RxJS to deal with huge data. 3.2.3. Node.js It is an open-source, JavaScript run-time environment based on event-driven architecture. This environment strive to optimise the scalability. 3.2.4. MongoDB Compass Visual tool for administration, creation and maintenance of MongoDB databases. 8 Application for Project Management 3.3. Third-party codes 3.3.1. Restify It is a Node.js web service framework used for building RESTful web services. It is used to create the server simply and gives an outstanding performance. 3.3.2. Socket.IO It is a JavaScript library for real-time web applications. It enables real-time, bidirectional and event-based communication. 3.3.3. NgRx It is a framework for building reactive applications in Angular providing state management and isolation of side effects. 3.3.4. Angular Material Library that provides common components based on Material Design guidelines and functionalities to give a custom window design. Design 9 CHAPTER 4. DESIGN 4.1. Overview Several technologies have been considered for the development of the front-end, such as React, Vue.js, but finally I have chosen Angular due to it is the best option to develop a Single Page Application (SPA), the usage of Typescript and Google powers it. The back-end is based on the Node.js technology together with Restify, as they are more suitable for a SPA development. The following diagram shows the structure used: Figure 4.1. Design diagram 10 Application for Project Management 4.2. Server The Node.js server is separated in two parts, on the one hand, the authentication part is a RESTful API and on the other hand, the applications own functionalities are part of an API that receives the requests via sockets. The following scheme describes the operation: Figure 4.2. Node.js diagram Design 11 4.3. Database architecture The database was designed with ‘Hackolade’ (see [13]) that is a visual data modelling software focused for NoSQL databases and has special functionalities that helps to take more advantage of this type of databases, in this case, embedded elements. The databases is composed of seven collections: - Users: collection storing all attributes of the user. The embedded arrays are used as reference; additionally, boards and projects have additional data related to himself. - Boards: it has the main structure of a board, references the tasks and the project related to itself. - Cards: it contains the information related to the task, having all the optional data in embedded documents and references the messages. - Projects: it has the whole structure of a project and only references the users and messages in the project. - Messages: it saves the messages created in the boards and projects collections. The priority attribute is used to identify if a message is created by the server or by the user. - Chats: it contains the users in the conversation and all the messages in an embedded array. - Logger: capped collection responsible for storing all requests and their outcome. 12 Application for Project Management Figure 4.3. MongoDB database design Design 13 4.4. Client The Angular framework is based on the existence of several modules, of which one module is the root and from this one others can be loaded lazily. This structure improves scalability and performance, each module consists of a variety of elements that allow the reusability of views, code and functionalities. The following diagram describes how it works: Figure 4.4. Angular diagram The application will be composed of three modules, app, auth and application, where ‘app’ is the root module and it is only used to load common features for ‘auth’ and ‘application’ and to route the client to one or other according to the URL and if the user is logged. 20 Application for Project Management Figure 5.1. Root module configuration On the other hand, the AppRoutingModule configuration of the previous figure refers to the following lines of code, where routes to the authentication module or the application according to the path; additionally, if the user tries to access the application first checks if the access token exists and is correct. const routes: Routes = [ {path: 'auth', loadChildren: './modules/home/home.module#HomeModule'}, {path: 'app', loadChildren: './modules/application/application.module#ApplicationModule', canLoad: [AuthGuard]}, {path: '', redirectTo: 'auth', pathMatch: 'full'} ]; Figure 5.2. Root routing configuration 5.1.2. Authentication module The authentication module has a clear purpose; therefore, it only imports the necessary modules for its operation making it a fast module to load. Only the different components used have been declared and the material design and translate modules have been imported. The module consists of five components, the log in, sign up and the password change process and finally, the dialog in which the email confirmation is performed. All components use the home.scss style sheet. These components communicate with the server API through AuthService and if the user logs in successfully, the token is saved. - home home.module.ts home.routing.ts home.scss - components log-in.component.ts sign.up.component.ts request.password.component.ts password.reset.component.ts auth.dialog.component.ts - views log-in.html sign.up.html request.password.html password.reset.html auth.dialog.html home.component.ts home.component.html Figure 5.3. Authentication module structure Development 21 5.1.3. Application module The module combines all the functionalities of the application; thus, it will have a large number of components and modules to allow all them. The most important imported modules are the following: - FlexLayout: provides a sophisticated layout API and enables to specify easily different layouts, sizing, and visibilities for different display devices. - Material Design: provides basic components following the material guidelines. - PrimeNg: provides more customizable tables than material design and charts. - Avatar: generates avatars bases on a username or an image. - Calendar: provides a calendar component that can display events on a month, week or day view. It also declares all custom directives and pipes that I created during the development. Group of functionalities separates the components of this module; however, it also has a group for small components that can be reused in other parts of the application such as the date picker or the attachments selector. All components are based on the use of the state management, which is explained in section 4.6.9. Developing the application with this technology improves the angular performance substantially by changing the change detection strategy to OnPush, which makes angular to update the DOM when it detects a change in the input. The NgRx module will carry out the server communications and consequently all changes in the state. Therefore, the data received from the server are not used directly, but are received through observables connected to the state machine. Lastly, to use the data from the state, I created the container components, which are in charge of combining the different elements of the state to build the desired object and pass it as a parameter to the child who shows it. The file structure is shown in the next page. 22 Application for Project Management - application application.module.ts application.routing.ts application.component.scss - components - application-components - menu-item-board-component board-menu-item.component.ts board-menu-item.html - board-components - board-home board.home.component.ts board.home.html - board-creator-dialog board.create.dialog.component.ts board.create.dialog.html - board-container board.container.component.ts board.container.html - board board.component.ts board.html - board-list board-card-list.component.ts board-card-list.html - board-item board-card-item.component.ts board-card-item.html - board-item-dialog board-card-item.dialog.container.ts board-card-item.dialog.container.html board-card-item.dialog.component.ts board-card-item.dialog.html - board-settings-dialog board.settings.dialog.container.ts board.settings.dialog.container.html board.settings.dialog.component.ts board.settings.dialog.html - timesheet-components - timesheet-weekly-insert timesheet.weekly.insert.component.ts timesheet.weekly.insert.html - dashboard-components - dashboard dashboard.component.ts dashboard.html - calendar-components - calendar calendar.component.ts calendar.html - common-components - activity activity.viewer.component.ts activity.viewer.html activity.message.component.ts activity.message.html - attachments attachment.selector.component.ts attachment.selector.html attachment.avatar.component.ts attachment.avatar.html attachment.upload.dialog.component.ts attachment.upload.dialog.html - checklist checklist.component.ts checklist.html - datepicker datepicker.component.ts datepicker.html - members members.selector.component.ts members.selector.html members.avatar.component.ts members.avatar.html - priority priority.selector.component.ts priority.selector.html - styles board.scss timesheet.scss common.scss application.component.ts application.component.html Figure 5.4. Application module structure Development 23 5.1.4. Authentication service This service is responsible for making HTTP requests related to authentication; in addition, it also adds functions to save the access token and decode it to check if it is valid or obtain the containing data. The HttpClient Angular module perform the HTTP requests, it can make any type of request and return the parsed response to the object indicated as observable. The following example shows the log in function of the service and the usage. logIn(email: string, password: string): Observable<{token: string, user: JSON}> { const params = {'email': email, 'password': password}; return this.http.post<{token: string, user: JSON}>( environment.server.url + AuthURLs.base + AuthURLs.logIn, params ); } Figure 5.5. Log in function this.userAuth.logIn(email, password).subscribe( response => { this.request = false; // Stop animation this.userAuth.setToken(response.token); // Save access token this.router.navigate(['../app']); // Navigate to application }, error => { this.request = false; // Stop animation switch (error.status) { /* Show error */ } } ); Figure 5.6. Log in function usage 24 Application for Project Management 5.1.5. Socket service The socket service makes almost all requests to the server within the application module. The service is based on two basic functions, which will be called from the state management to emit and listen to the different events. The creation of the socket and the different functions are carried out with the Socket.IO library. The socketIo function creates the socket with the URL of the server; in addition, the URL must include the access token. Once connected, as discussed in previous sections, this technology is eventbased, so all events are performed with the name of the event and an optional data. If the event has data, before emitting it, a timestamp will be added in order to enable error control in the state management. The following figures illustrates how to connect to the server and the functions for communicating with it. this.socket = socketIo( environment.server.url + '?token=' + localStorage.getItem('access_token') ); Figure 5.7. Create socket connection emit(event: string, data?: any): void { if (data !== undefined) { // Add timestamp and save it into state log } this.socket.emit(event, data); } listen(event: string): Observable<any> { return new Observable<any>( observer => { this.socket.on(event, (data: any) => { observer.next(data); }); // Dispose of the event listener when unsubscribed return () => this.socket.off(event); }); } Figure 5.8. Emit and listen functions in socket service Development 25 5.1.6. Translate service This service is part of the ngx-translate module and allows instant translation among languages without having to compile the client in each language. The service is configured in the SharedModule module, which is imported into the root module. In the module constructor are inserted the different languages supported by the application, English (UK and US) and Spanish, the English versions differ in the format of the dates, a fact that the application takes into account in its components, for example, in timesheets. The format of language files are JSON files, so accessing a value in the application is simple. { "HOME": { "LogIn": { ”Title": "Log in", "Subtitle": "into your ProjectManager account", }, ... }, ... } Figure 5.9. Language file example When initiating the application for the first time, I chose to use the browser language by default and save it in the local storage, in case the language is changed, the saved variable will be modified; therefore, the next time the application will use the corresponding language. Once configured, there are several ways to access the values of the language files; however, two have been used in the project, the pipe 'translate' in HMTL and the translate service in TypeScript. {{ 'HOME.LogIn.Title' | translate }} Figure 5.10. Getting translation in HTML this.translate.instant('HOME.LogIn.Title') Figure 5.11. Getting translation in TypeScript 26 Application for Project Management 5.1.7. Directives The directives allows creating custom behaviours to elements in the DOM. During the development, I created five directives, three for text inputs and two for detecting the click events: - autoFocus: it is used to autoselect an input when it appears in the DOM. - AutoSizeInput: it allows fitting the width of an input automatically while it grows or decrease. - autoSizeTextArea: it allows to fit the height of a textarea while it increase or decrease the number of lines. - clickInside: it emits an event when the user clicks inside the element. - clickOutside: it emits an event when the user outer the element. @Directive({ selector: '[clickInside]' }) export class ClickInsideDirective { constructor(private _elementRef: ElementRef) { } @Output() public clickInside = new EventEmitter<MouseEvent>(); @HostListener('document:click', ['$event', '$event.target']) public onClick(event: MouseEvent, targetElement: HTMLElement): void { if (!targetElement) { return; } if (this._elementRef.nativeElement.contains(targetElement)) { this.clickInside.emit(event); } } } Figure 5.12. Click inside directive code Development 27 5.1.8. Pipes The pipes takes the input data and transforms it to a desired output, using pipes allows the developer to repeat the same transformations repeatedly in different components. I created the next four pipes in this project: - datepipe: it allows to change the language provider of the original Angular date pipe at runtime using the translate service. - numberpipe: it takes the current language of the application and transforms the input number into the corresponding language format. - timeAgo: returns the difference between the input time and now in the current language. - highlight: it returns the text highlighted where the text matches the filter criteria. @Pipe({ name: 'numberpipe' }) export class NumberPipe implements PipeTransform { constructor(private translate: TranslateService) { } transform(value: any, locale: string = null): string | null { if (value === undefined || value === null) { return undefined; } else if (typeof(value) !== 'number') { return value; } if (locale !== null) { return value.toLocaleString(locale); } else { return value.toLocaleString(this.translate.currentLang); } } } Figure 5.13. Numberpipe directive code 28 Application for Project Management 5.1.9. Reactive state management The reactive state management is based on the framework NgRx, using this technology all the data comes from one source, the store. It provides significant benefits: - When an application is growing, keeping track of the state changes is messy and difficult to maintain, using NgRx the state is handled only in the store. - Having all the changes are in the same place makes easier debugging and testing. - Enabling to have a better performance using OnPush as detection change strategy. The next diagram summarises the workflow of this framework and the explanation in the most common case: Figure 5.14. NgRx flow diagram The component dispatches an action, this action trigger an effect that will emit an event to the server and wait for an answer, once received the answer, the resultstate will execute de side effect calling the reducer, which will update the store. When the store have a new state, the selector in the components will provide new values and update the views. Development 29 Once the basic operation has been explained, the following figures show the operation of the project Store: this._store.dispatch(new AddCardList({ id: this.board._id, name: this.newCardListFormControl.value, position: this.board.lists.length })); Figure 5.15. AddCardList action dispatcher The effect receives the dispatched action and executes the addCardList function of the boards service, which will emit the event and once received the response, it will trigger the side effect through the action AddCardListSuccess. @Effect() addCardList$: Observable<Action> = this._actions$.pipe( ofType<boardActions.AddCardList>(boardActions.EBoardActions.AddCardList), switchMap(action => this._boardsService.addCardList(action.payload)), switchMap((cardlist: ICardList) => of(new boardActions.AddCardListSuccess({cardList: cardlist}))) ); Figure 5.16. Effect AddCardList Figure 5.17. Add Card List events 36 Application for Project Management 5.2.3. Controllers In order to maintain a solid and clear structure each functional group of the application has its own controller. Each controller has defined a series of functions that always return a JSON response regardless of the protocol used. In the case of HTTP, the responses must contain the status code as indicated in its definition along with an optional response. The server framework also requires calling the next function to enable it to continue with the next handler if it exists. function http(req, res, next){ const params = sanitize(req.body); // Access database using params res.send(200, response); return next(); } Figure 5.26. HTTP request handling example In the case of the WebSocket protocol, the emission of the event must take into account whether the event is only for who made the request, for all the room members or only for the rest of the room members. For a better visualization of where one or other is used, as a general rule, I decided that the route file will send the destination sockets of the event as parameter. Thus, the controller functions does not need to change. function onlySocket(socket, parameters){ const params = sanitize(parameters); // Access database using params socket.emit('[Example] Add Example Success', response); } function multipleSockets(sockets, parameters){ const params = sanitize(parameters); // Access database using params sockets.emit('[Example] Add Example Success', response); } Figure 5.27. WebSocket event handling example Development 37 In both protocols, before executing any function we must ensure that the data of the request is safe, to achieve it, the library 'mongo-sanitize' is used stripping out any keys that start with '$' in the input avoiding Query Selector Injection Attacks (see [15]). 5.2.4. Emails Emails are sent using the nodemailer library, which must be configured during server start-up. The configuration is as follows: const mailer = nodemailer.createTransport({ host: ‘smtp.projectmanager.com’, port: 465, secure: true, auth: { user: '[email protected]', pass: 'XXXXXXXX' } }); Figure 5.28. Nodemailer configuration I created the file email.service.js in order to generalize the sending of emails in the whole application. This file contains the sendEmail function and all the templates of email of the application, thus, to send an email I just need to indicate the destination email and the template to be used. Part of the file code is as follows: 38 Application for Project Management function sendEmail(toEmail, template){ const email = { from: ’[email protected]', to: toEmail, subject: template.subject, html: template.content, attachments: [{ filename: 'icon.png', path: 'icon.png', cid: 'unique@icon' }] } mailer.sendMail(email, function(error, info){ if (error) { /* Return error */ } }); } const EmailConfirmation = { 'en': { 'subject': 'Confirm your account', 'content': fs.readFileSync(dirTemplates + '/sign-up/en.html').toString() }, 'es': { 'subject': 'Confirme su cuenta', 'content': fs.readFileSync(dirTemplates + '/sign-up/es.html').toString() } } Figure 5.29. Send email function and email confirmation object Development 39 5.2.5. Sensible data The developed application contains sensitive data that should not be visible, for example, the passwords of users. These data must be stored encrypted or hashed. Currently, the project only contains the password as data to be protected. The safest way to save a password is to use a hash, which is a one-way encryption that converts the plaintext to a secret code; therefore, there is no way back to the actual plaintext from the hashed version. The hashing will be performed with the Argon2 library, which implements the use of random salt automatically, which avoids the use of rainbow tables (see [16]). The library uses the next function: argon2.hash(password).then(hash => { // Use hashed password }).catch(err => { // Return error }); Figure 5.30. Hash plaintext example Password verification is achieved with the function: argon2.verify(passwordHashed, passwordToCompare).then(match => { if (match) { // Correct password } else { // Not valid password } }).catch(err => { // Return error }); Figure 5.31. Hash verification example 40 Application for Project Management 5.2.6. Actions log The action log is a record of all calls made to the server. The use of this log allows to have record of improper actions of users and in case of errors, these can be replicated. Each log entry must contain the ID or IP of the user who makes the request, the action that is executed and the result of the request; it also contains the parameters that you have received and, in case of error, the exception error. I developed the logger service to implement this functionality. This service contains two enumerations, one with the possible actions and the other with possible results, and finally the insertLog function that saves the entry in the database. logger.insertLog( req.connection.remoteAddress, logger.actions.Insert, 'Sign Up', params, logger.results.Ok ); Figure 5.32. Logging sign up successful action In the next page, the figure shows some rows of this collection. The id during the action ‘Log In’ represents the original IP address of the client; however, as the environment is working in local, the value is the loopback address. Development 41 Figure 5.33. Actions log 42 Application for Project Management 5.2.7. Errors The handling of responses if any authentication or internal server error occurs is different depending on the protocol used. If the error occurs in HTTP, the restify-errors library is used to return the response with the status code of the error type. The following example responds the request with the status 401 with the object error as data. return next(new restifyerrors.UnauthorizedError(error)) Figure 5.34. Returning error in HTTP example In the case of WebSockets there is no common dealing with errors; therefore, I created the error service that contains the handling of errors with the aim of sending the errors with the optimal structure for the client. class CustomError extends Error { constructor(message, timestamp) { super(message) this.method = message.method this.message = message.message this.timestamp = timestamp } toJSON() { return { error: { method: this.method, message: this.message, timestamp: this.timestamp } } } } function sendError(socket, action, errorToLog, errorToSend, timestamp) { // Log Error socket.emit(action, (new CustomError(errorToSend, timestamp).toJSON())); } Figure 5.35. Custom error handling in WebSockets Development 43 Lastly, the following function must be called: return socketerrors.sendError ( socket, socketerrors.types.Board.Action, error, socketerrors.types.Board.GetBoard, params.timestamp ); Figure 5.36. Returning error in WebSockets example 44 Application for Project Management CHAPTER 6. TEST 6.1. Test Having a set of functional tests to fulfil is needed in order to ensure that the current functionalities are working while the development keeps growing up. The tests are separated by functionalities and as new features are added, they will be added independently. This way, each test group will be easier to perform and keep track of it. Table 6.1. Authentication functionalities tests Test Google Chrome Mozilla Firefox Microsoft Edge Sign up Verify account Log in Recover password Log out Try to enter app without token Table 6.2. Board functionalities tests Test Google Chrome Mozilla Firefox Microsoft Edge Create board Manage users from board Add / Move / Delete lists Add / Move / Delete tasks Check all tasks functionalities Manage users from tasks Simultaneity among users in tables Test 45 6.2. Results A few months after the beginning of the development of the project, as discussed in other sections, the first version of the application meets part of the functionalities and requirements but there is still work to be done. The client can perform the basic functions of authentication, sign up, thus he will receive an email to confirm his mail, recover the password, so he will also receive an email with further instructions or log in and access the application. Figure 6.1. Log in and sign up views, respectively Figure 6.2. Registration and password request emails, respectively