Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { DebugElement, NgModule } from '@angular/core';
- import { ComponentFixture, TestBed, async } from '@angular/core/testing';
- import { FormsModule } from '@angular/forms';
- import { By } from '@angular/platform-browser';
- import { Router, RouterModule } from '@angular/router';
- import { Http } from '@angular/http';
- import { DashboardComponent } from './dashboard.component';
- import { PatientListComponent } from '../patient-list/patient-list.component';
- import { PatientListItemComponent } from '../patient-list-item/patient-list-item.component';
- import { AuthenticationService } from '../authentication.service';
- import { Authentication } from '../authentication';
- import { PatientSummaryService } from '../patient-summary/patient-summary.service';
- import { PatientSummary } from '../patient-summary/patient-summary';
- import { StaffFilterPipe } from '../staff-filter.pipe';
- import { testData } from '../patient-list/patient-list.test-data';
- import { MockAuthService, MockPatientSummaryService, RouterStub, HttpMock } from './dashboard.mocks';
- /*
- * DebugElement and By are currently not used. I have left them in the import statements above,
- * because any test suite WILL use them when it is fully developed.
- */
- describe( "DashboardComponent", ()=>{
- var component : DashboardComponent;
- var fixture : ComponentFixture<DashboardComponent>;
- beforeEach(
- async(
- ()=>{
- TestBed.configureTestingModule(
- {
- imports: [ RouterModule, FormsModule ],
- declarations: [ DashboardComponent, PatientListComponent, PatientListItemComponent, StaffFilterPipe ],
- providers: [
- { provide: AuthenticationService, useClass: MockAuthService },
- { provide: PatientSummaryService, useClass: MockPatientSummaryService },
- { provide: Router, useClass: RouterStub },
- { provide: Http, useClass: HttpMock }
- ]
- }
- ).compileComponents();
- console.log( "Compile components is called" );
- } ));
- beforeEach(()=>{
- fixture = TestBed.createComponent( DashboardComponent );
- var authService:MockAuthService = fixture.debugElement.injector.get(AuthenticationService);
- authService.fakeAnAuth("drbanks");
- var patientService: MockPatientSummaryService = fixture.debugElement.injector.get(PatientSummaryService);
- patientService.fakeAListChange( testData );
- fixture.detectChanges();
- component = fixture.componentInstance;
- console.log( "Fixture is defined" );
- });
- describe("component setup verifications", ()=>{
- it( "component has an authentication", async(
- ()=>{
- expect(component.credentials instanceof Authentication).toBe( true );
- expect(component.credentials.username).toBe("drbanks");
- }
- ) );
- it( "component has a patient list", async(
- ()=>{
- expect( Array.isArray( component.patientSummary ) ).toBe(true, "The patientSummary attribute is an array.");
- expect( component.patientSummary.length ).toBeGreaterThan( 0, "The patientSummary array has more than zero elements." );
- for( var patient of component.patientSummary ){
- expect( patient instanceof PatientSummary ).toBe( true, "Each patientSummary element is a PatientSummary object." );
- }
- }
- ) );
- });
- } );
- import { Injectable } from '@angular/core';
- import { testData } from '../patient-list/patient-list.test-data';
- import { PatientSummaryService } from '../patient-summary/patient-summary.service';
- import { PatientSummary } from '../patient-summary/patient-summary';
- import { Authentication } from '../authentication';
- import { AuthenticationService } from '../authentication.service';
- import { Staff } from '../staff';
- @Injectable()
- export class RouterStub {
- navigate( parts : string[] ){
- return parts;
- }
- }
- @Injectable()
- export class MockAuthService extends AuthenticationService {
- sendAuthRequest( restUrl: string, postData : any ){
- //override do nothing
- }
- fakeAnAuth( userid : string ){
- var banks : Staff = new Staff();
- var owens : Staff = new Staff();
- banks.userid = "drbanks";
- banks.groupid = ["doctors","super_user"];
- owens.userid = "owens";
- owens.groupid = ["doctors"];
- var options : any = {
- drbanks: new Authentication( "drbanks", "test_token_1324", banks ),
- drowens: new Authentication( "drowens", "test_token_5123", owens )
- };
- if( typeof options[ userid ] != "undefined" ){
- //emit the selected credential
- this.verifySuccess( options[ userid ] );
- }else{
- //clear credentials and emit an invalidate signal
- this.clearCreds();
- }
- }
- }
- @Injectable()
- export class MockPatientSummaryService extends PatientSummaryService {
- responded : boolean = false;
- constructor() {
- super( null );
- }
- getActive(){
- if (this.responded ) return;
- this.updatedList.emit( testData );
- this.responded = true;
- }
- fakeAListChange( list : PatientSummary[] ){
- this.updatedList.emit( list );
- }
- }
- @Injectable()
- export class HttpMock {}
- import { Component, Input } from '@angular/core';
- import { Router } from '@angular/router';
- import { Authentication } from '../authentication';
- import { AuthenticationService } from '../authentication.service';
- import { PatientSummaryService } from '../patient-summary/patient-summary.service';
- import { PatientSummary } from '../patient-summary/patient-summary';
- @Component(
- {
- moduleId: module.id,
- selector: 'dashboard',
- template: `
- <div class="container" *ngIf="credentials.valid">
- <div class="col-xs-12 filterOptions">
- <span class="col-xs-12">
- <button class="btn btn-small btn-default pull-right" (click)="toggleFilterView()">Toggle Filters</button>
- <h4>Filter Options</h4>
- </span>
- <span *ngIf="viewFilters">
- <label>
- <input type='checkbox' [(ngModel)]="filterList" />
- Filter the list for <strong>only</strong> patients linked to your account.
- </label>
- <div class="form-group">
- <label>Filter By Patient Name</label>
- <input class="form-control" [(ngModel)]="nameFilter" placeholder="Patient name in full or in part." />
- </div>
- </span>
- </div>
- <h1>Priority Patients</h1>
- <patient-list id="priority_patients" [sourceData]="todaysPatientList | staffFilter : acceptableStaff" (clickPatient)="selectPatient($event)"></patient-list>
- <h1>Patients Records <small>(Not Yet Complete)</small></h1>
- <patient-list id="patient_records_backlog" [sourceData]="nonActivePatientList | staffFilter : acceptableStaff" (clickPatient)="selectPatient($event)"></patient-list>
- </div>`,
- styles: [
- `.filterOptions {
- background-color: hsla( 187, 55%, 90%, 0.5 );
- padding: 1em;
- border: solid 3px black;
- border-radius: 1em;
- margin-bottom: 1em;
- }`
- ]
- }
- )
- export class DashboardComponent {
- credentials : Authentication = new Authentication(null,null,null);
- viewFilters: boolean = false;
- nameFilter: string = "";
- filterList: boolean = true;
- patientSummary: PatientSummary[];
- constructor( private patientSummaryService : PatientSummaryService,
- private authService : AuthenticationService,
- private router : Router ){}
- ngOnInit(){
- var app = this;
- this.patientSummaryService.updatedList.subscribe(
- (list : PatientSummary[] ) => {app.setPatientSummaryList(list);}
- );
- this.authService.newCreds.subscribe(
- (creds : Authentication) => this.credentials = creds
- );
- this.authService.invalidate.subscribe(
- (obj : any) => this.credentials = new Authentication(null,null,null)
- );
- }
- setPatientSummaryList(list: PatientSummary[]) {
- var app = this;
- list.sort((a: PatientSummary, b: PatientSummary) => {
- var dateA = app.extractDate(a);
- var dateB = app.extractDate(b);
- if (dateA > dateB) return 1;
- if (dateA < dateB) return -1;
- return 0;
- });
- this.patientSummary = list;
- }
- extractDate(item: PatientSummary) {
- var date = item.arrivalTime;
- if (date === null || date < item.visit.date) {
- date = item.visit.date;
- }
- return date;
- }
- nameFilterFunction(item: PatientSummary) {
- if (this.nameFilter == "") return true;
- if (typeof item == "object" && typeof item.name != "undefined") {
- var index = item.name.indexOf(this.nameFilter);
- return (index !== -1);
- }
- return false;
- }
- toggleFilterView() {
- this.viewFilters = !this.viewFilters;
- }
- /**
- * Returns a list of patients in ascending order (oldest first) of items
- * that are today and are assigned to a room.
- */
- get todaysPatientList() {
- var app = this;
- if (!Array.isArray(this.patientSummary)) return [];
- var list = this.patientSummary.filter(
- (item: PatientSummary) => {
- var date = app.extractDate(item);
- var now = new Date();
- var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
- var tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
- return date >= today && date <= tomorrow;
- }).filter((item: PatientSummary) => {
- if (typeof item == "object" && typeof item.location == "object" && typeof item.location.room !== null) {
- return item.location.room != "No Room Assignment";
- } else {
- return true;
- }
- });
- return list.filter((item) => {return app.nameFilterFunction(item);});
- }
- /**
- * Returns a list of patients in descending order (most recent first) of items
- * that do not appear in the todaysPatientList attribute;
- */
- get nonActivePatientList() {
- if (!Array.isArray(this.patientSummary)) return [];
- var app = this;
- var list = this.todaysPatientList;
- var nonActiveList = this.patientSummary.filter((obj: PatientSummary) => {
- var index = list.indexOf(obj);
- return (index == -1);
- });
- nonActiveList.reverse();
- return nonActiveList.filter((item) => {return app.nameFilterFunction(item);});;
- }
- get acceptableStaff() {
- if (!this.filterList) {
- return "any";
- } else {
- var user = "any";
- if (this.credentials instanceof Authentication) {
- user = this.credentials.username;
- }
- if (user === null) user = "any";
- return user;
- }
- };
- selectPatient( patient : PatientSummary ){
- var id = patient.medfaceId;
- this.router.navigate(['/detail',id]);
- }
- }
- import {Injectable, Output, EventEmitter} from '@angular/core';
- import {Http, Response} from '@angular/http';
- import {Authentication} from '../authentication';
- import {PatientSummary} from './patient-summary';
- import {Observable} from 'rxjs/Observable';
- import '../rxjs-operators';
- @Injectable()
- export class PatientSummaryService {
- updateFrequency: number = 60000; /* every 1 minutes */
- lastUpdateTime: Date = new Date();
- lastList: PatientSummary[] = [];
- timeoutId: any = null;
- auth: Authentication = new Authentication(null, null, null);
- @Output() updatedList: EventEmitter<PatientSummary[]> = new EventEmitter<PatientSummary[]>();
- constructor(private http: Http) {};
- useCredentials(creds: Authentication) {
- this.auth = creds;
- if (creds.valid == false) {
- this.stopHttpRequests();
- }
- else if (this.timeoutId == null) {
- this.startHttpRequests();
- }
- };
- /**
- * If the timer is still set, cancel the timer and clear all lists by
- * emitting an emty list set.
- */
- stopHttpRequests() {
- if (this.timeoutId) {
- clearTimeout(this.timeoutId);
- this.timeoutId = null;
- this.lastUpdateTime = new Date();
- this.lastList = [];
- this.updatedList.emit( this.lastList );
- }
- }
- /**
- * Start collecting lists again.
- */
- startHttpRequests() {
- this.getActive();
- }
- getActive() : void {
- var auth = this.auth;
- if (!auth.valid) {
- this.stopHttpRequests();
- return null;
- }
- const restUrl = "../rest.php";
- let postData = {
- username: auth.username,
- token: auth.token,
- command: "getActiveSummaries",
- use_cache: true,
- version: "2.0"
- };
- var service = this;
- var observable = this.http.post(restUrl, JSON.stringify(postData))
- .map((data) => {return service.extractData(data);})
- .catch( (err : any ) => { service.handleError( err ); return null; } );
- observable.subscribe(
- (dataPacket : {
- lastUpdated: Date,
- activeList : any
- } ) => {
- if (service.lastUpdateTime.toTimeString() != dataPacket.lastUpdated.toTimeString()) {
- service.lastUpdateTime = dataPacket.lastUpdated;
- service.lastList = dataPacket.activeList;
- service.updatedList.emit(service.lastList);
- }
- service.setNewTimer();
- },
- (error) => {
- service.handleError(error);
- service.setNewTimer();
- }
- );
- };
- setNewTimer() {
- var service = this;
- this.timeoutId = setTimeout(() => {service.getActive();}, service.updateFrequency);
- };
- convertDateObjects(obj: any) {
- if (obj === null) return obj;
- var soughtFields = ['year', 'month', 'day', 'hour', 'minute'];
- var objFound : any = null;
- if (typeof obj == "object") {
- objFound = true;
- for (var key of soughtFields) {
- if (typeof obj[key] == "undefined") {
- objFound = false;
- break;
- }
- }
- if (objFound) {
- if (obj.year !== 1920) {
- return new Date(obj.year, obj.month, obj.day, obj.hour, obj.minute);
- } else {
- return null;
- }
- } else {
- for (var i in obj) {
- if (obj.hasOwnProperty(i)) {
- var item = this.convertDateObjects(obj[i]);
- obj[i] = item;
- }
- }
- }
- }
- return obj;
- };
- extractData(response: Response) {
- var body = response.json();
- body = this.convertDateObjects(body);
- console.log(body);
- if (typeof body.error !== "undefined") {
- throw body.error;
- }
- var dataPacket = body.data;
- return dataPacket;
- };
- handleError(error : any) {
- console.error("Error received in PatientSummaryService.", error);
- };
- }
- import { Injectable, Output, EventEmitter } from '@angular/core';
- import { Http } from '@angular/http';
- import './rxjs-operators';
- import { Authentication } from './authentication';
- @Injectable()
- export class AuthenticationService
- {
- auth : Authentication = new Authentication( null, null, null );
- username: string;
- token: string;
- cookie_load_complete : boolean = false;
- @Output() invalidate : EventEmitter<any> = new EventEmitter();
- @Output() newCreds : EventEmitter<any> = new EventEmitter();
- constructor( private http : Http ){}
- loadCredsFromCookie(){
- if( !this.cookie_load_complete ){
- var cookieString = document.cookie;
- //using ECMA 2015 for cookie management;
- let userMatch = cookieString.match( /username=([^;]+)/ );
- let tokenMatch = cookieString.match(/token=([^;]+)/);
- if( userMatch !== null && tokenMatch!== null ){
- let user = userMatch[1];
- let token = tokenMatch[1];
- this.testToken(user, token);
- }
- }
- this.cookie_load_complete = true;
- }
- saveCredsInCookie( username : string , token : string ){
- //using ECMA 2015 for cookie management
- let date = new Date();
- let year = date.getFullYear();
- let month = date.getMonth();
- let day = date.getDate();
- let hours = date.getHours();
- let minutes = date.getMinutes();
- let tomorrow = new Date( year, month, day + 1, hours, minutes );
- let _24hours = tomorrow.toUTCString();
- document.cookie = `username=${username}; expires=${_24hours}`;
- document.cookie = `token=${token}; expires=${_24hours}`;
- }
- setUserName( name :string ){ this.username = name; }
- setToken( token: string ){
- let username = this.username;
- this.token = token;
- this.saveCredsInCookie( username, token );
- }
- clearCreds(){
- this.username = null;
- this.token = null;
- this.saveCredsInCookie(null,null);
- this.invalidate.emit( null );
- }
- testToken( username : string, token : string ){
- this.setUserName( username );
- const restUrl = "../rest.php";
- let postData = { command: "authenticate", username, token };
- this.sendAuthRequest( restUrl, postData );
- };
- testCredentials( userName:string, password:string ) {
- this.setUserName( userName );
- const restUrl = "../rest.php";
- let postData = { command: "authenticate", username: userName, password };
- this.sendAuthRequest( restUrl, postData );
- };
- sendAuthRequest( restUrl: string, postData : any ){
- postData.version = "2.0";
- var service = this;
- var observable = this.http
- .post(restUrl, JSON.stringify(postData) )
- .map(
- this.extractData
- )
- .catch( service.handleError );
- observable.subscribe(
- (success : any ) => this.verifySuccess(success),
- ( err : any ) => service.handleError( err, {} )
- );
- };
- verifySuccess( data : Authentication ){
- if( data.valid == true ){
- //successful login
- if( this.token !== data.token ){
- var auth : Authentication = new Authentication( data.username, data.token, data.staff );
- this.auth = auth;
- this.setToken( data.token );
- this.newCreds.emit( auth );
- }
- } else {
- this.clearCreds();
- this.handleError( "Provided credentials are not valid.", {} );
- }
- }
- extractData( response : any ){
- var body = response._body;
- var jBody = JSON.parse( body );
- return jBody.data;
- }
- handleError( error : any, observable : any ) : any{
- console.error( `Error received. ${error}` );
- this.setUserName("");
- this.setToken( "" );
- this.invalidate.emit( { errorMsg: error } );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement