diff --git a/vsd-app/ClientApp/.prettierignore b/vsd-app/ClientApp/.prettierignore new file mode 100644 index 00000000..37e782fd --- /dev/null +++ b/vsd-app/ClientApp/.prettierignore @@ -0,0 +1,18 @@ +node_modules + +package-lock.json + +dist +build +coverage + +openshift +sonar-runner +uploads + +.vscode + +**/vendor + +*.html + diff --git a/vsd-app/ClientApp/.prettierrc b/vsd-app/ClientApp/.prettierrc new file mode 100644 index 00000000..bc87cb67 --- /dev/null +++ b/vsd-app/ClientApp/.prettierrc @@ -0,0 +1,16 @@ +{ + "printWidth": 120, + "tabWidth": 2, + "useTabs": false, + "semi": true, + "singleQuote": true, + "trailingComma": "none", + "bracketSpacing": true, + "bracketSameLine": true, + "requirePragma": false, + "insertPragma": false, + "proseWrap": "never", + "endOfLine": "lf", + "arrowParens": "always", + "htmlWhitespaceSensitivity": "ignore" +} diff --git a/vsd-app/ClientApp/package-lock.json b/vsd-app/ClientApp/package-lock.json index 8c0dc543..2c6fb0a8 100644 --- a/vsd-app/ClientApp/package-lock.json +++ b/vsd-app/ClientApp/package-lock.json @@ -9198,6 +9198,18 @@ "integrity": "sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks=", "dev": true }, + "prettier": { + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", + "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", + "dev": true + }, + "prettier-plugin-organize-imports": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/prettier-plugin-organize-imports/-/prettier-plugin-organize-imports-4.1.0.tgz", + "integrity": "sha512-5aWRdCgv645xaa58X8lOxzZoiHAldAPChljr/MT0crXVOWTZ+Svl4hIWlz+niYSlO6ikE5UXkN1JrRvIP2ut0A==", + "dev": true + }, "process": { "version": "0.11.10", "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", diff --git a/vsd-app/ClientApp/package.json b/vsd-app/ClientApp/package.json index 1afa1c73..64277fd7 100644 --- a/vsd-app/ClientApp/package.json +++ b/vsd-app/ClientApp/package.json @@ -12,7 +12,9 @@ "build:ssr": "npm run build -- --app=ssr --output-hashing=media", "test": "ng test", "lint": "ng lint", - "e2e": "ng e2e" + "e2e": "ng e2e", + "format": "prettier --loglevel=warn --check \"./src/**/*.{js,jsx,ts,tsx,css,scss}\"", + "format-fix": "prettier --loglevel=warn --write \"./src/**/*.{js,jsx,ts,tsx,json,css,scss}\"" }, "private": true, "dependencies": { @@ -81,6 +83,8 @@ "karma-jasmine": "~1.1.2", "karma-jasmine-html-reporter": "^0.2.2", "mini-css-extract-plugin": "^0.5.0", + "prettier": "^2.8.8", + "prettier-plugin-organize-imports": "^4.1.0", "protractor": "~5.4.0", "ts-node": "~7.0.0", "tslint": "~5.11.0", diff --git a/vsd-app/ClientApp/src/app/app-routing.module.ts b/vsd-app/ClientApp/src/app/app-routing.module.ts index 28111ce5..05dc28f8 100644 --- a/vsd-app/ClientApp/src/app/app-routing.module.ts +++ b/vsd-app/ClientApp/src/app/app-routing.module.ts @@ -16,27 +16,27 @@ const routes: Routes = [ }, { path: 'victim-application', - component: VictimApplicationComponent, + component: VictimApplicationComponent }, { path: 'ifm-application', - component: IfmApplicationComponent, + component: IfmApplicationComponent }, { path: 'witness-application', - component: WitnessApplicationComponent, + component: WitnessApplicationComponent }, { path: 'submit-invoice', - component: SubmitInvoiceComponent, + component: SubmitInvoiceComponent }, { path: 'application-cancelled', - component: ApplicationCancelledComponent, + component: ApplicationCancelledComponent }, { path: 'application-success', - component: ApplicationSuccessComponent, + component: ApplicationSuccessComponent }, { path: '**', component: NotFoundComponent } ]; @@ -46,4 +46,4 @@ const routes: Routes = [ exports: [RouterModule], providers: [] }) -export class AppRoutingModule { } +export class AppRoutingModule {} diff --git a/vsd-app/ClientApp/src/app/app.component.scss b/vsd-app/ClientApp/src/app/app.component.scss index ef03d217..b2503a92 100644 --- a/vsd-app/ClientApp/src/app/app.component.scss +++ b/vsd-app/ClientApp/src/app/app.component.scss @@ -8,7 +8,7 @@ header { border-bottom: 4px solid #fcba19; } -.warning{ +.warning { color: red !important; } @@ -23,7 +23,7 @@ header { margin-left: 0; } -.no-gutter > [class*="col-"] { +.no-gutter > [class*='col-'] { padding-right: 0; padding-left: 0; } @@ -698,8 +698,8 @@ textarea.form-control { margin-bottom: 5px; } - input[type="checkbox"], - input[type="radio"] { + input[type='checkbox'], + input[type='radio'] { margin-right: 5px; } @@ -717,7 +717,7 @@ textarea.form-control { } ::ng-deep .terms { - input[type="text"] { + input[type='text'] { margin-left: 15px; } diff --git a/vsd-app/ClientApp/src/app/app.component.spec.ts b/vsd-app/ClientApp/src/app/app.component.spec.ts index 861cc58b..87d2f51a 100644 --- a/vsd-app/ClientApp/src/app/app.component.spec.ts +++ b/vsd-app/ClientApp/src/app/app.component.spec.ts @@ -1,7 +1,5 @@ import { TestBed, async } from '@angular/core/testing'; -import { - RouterTestingModule -} from '@angular/router/testing'; +import { RouterTestingModule } from '@angular/router/testing'; import { AppComponent } from './app.component'; import { BreadcrumbComponent } from './breadcrumb/breadcrumb.component'; @@ -9,11 +7,8 @@ import { BreadcrumbComponent } from './breadcrumb/breadcrumb.component'; describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - declarations: [ - AppComponent, - BreadcrumbComponent - ], - imports: [ RouterTestingModule ] + declarations: [AppComponent, BreadcrumbComponent], + imports: [RouterTestingModule] }).compileComponents(); })); diff --git a/vsd-app/ClientApp/src/app/app.component.ts b/vsd-app/ClientApp/src/app/app.component.ts index a77b74eb..0711ddfe 100644 --- a/vsd-app/ClientApp/src/app/app.component.ts +++ b/vsd-app/ClientApp/src/app/app.component.ts @@ -4,15 +4,15 @@ import { isDevMode } from '@angular/core'; import 'rxjs/add/operator/filter'; import { HeaderTitleService } from './services/titile.service'; import { LookupService } from './services/lookup.service'; -import { ConfigService } from "./services/config.service"; -import { Configuration } from "./interfaces/configuration.interface"; +import { ConfigService } from './services/config.service'; +import { Configuration } from './interfaces/configuration.interface'; import * as moment from 'moment-timezone'; import { environment } from '../environments/environment'; @Component({ selector: 'app-root', templateUrl: './app.component.html', - styleUrls: ['./app.component.scss'], + styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { title = ''; @@ -28,7 +28,7 @@ export class AppComponent implements OnInit { private router: Router, private headerTitleService: HeaderTitleService, private lookupService: LookupService, - private configService: ConfigService, + private configService: ConfigService ) { this.isDevMode = isDevMode(); this.router.events.subscribe((event) => { @@ -48,7 +48,7 @@ export class AppComponent implements OnInit { } ngOnInit() { - this.headerTitleService.title.subscribe(updatedTitle => { + this.headerTitleService.title.subscribe((updatedTitle) => { this.title = updatedTitle; }); @@ -59,35 +59,41 @@ export class AppComponent implements OnInit { } }); - this.configService.load() + this.configService + .load() .then((configuration) => { - console.log("Fetched Configuration:", configuration); + console.log('Fetched Configuration:', configuration); this.configuration = configuration; }) .catch((error) => { - console.error("Failed to fetch configuration:", error); + console.error('Failed to fetch configuration:', error); this.error = error; }); } isOutage() { - if (!this.configuration || !this.configuration.outageEndDate || !this.configuration.outageStartDate || !this.configuration.outageMessage) { + if ( + !this.configuration || + !this.configuration.outageEndDate || + !this.configuration.outageStartDate || + !this.configuration.outageMessage + ) { return false; } - const currentDate = moment().tz("America/Vancouver"); - const outageStartDate = moment(this.configuration.outageStartDate).tz("America/Vancouver"); - const outageEndDate = moment(this.configuration.outageEndDate).tz("America/Vancouver"); + const currentDate = moment().tz('America/Vancouver'); + const outageStartDate = moment(this.configuration.outageStartDate).tz('America/Vancouver'); + const outageEndDate = moment(this.configuration.outageEndDate).tz('America/Vancouver'); return currentDate.isBetween(outageStartDate, outageEndDate, null, '[]'); } generateOutageDateMessage(): string { - const startDate = moment(this.configuration.outageStartDate).tz("America/Vancouver").format("MMMM Do YYYY, h:mm a"); - const endDate = moment(this.configuration.outageEndDate).tz("America/Vancouver").format("MMMM Do YYYY, h:mm a"); - return "The system will be down for maintenance from " + startDate + " to " + endDate; + const startDate = moment(this.configuration.outageStartDate).tz('America/Vancouver').format('MMMM Do YYYY, h:mm a'); + const endDate = moment(this.configuration.outageEndDate).tz('America/Vancouver').format('MMMM Do YYYY, h:mm a'); + return 'The system will be down for maintenance from ' + startDate + ' to ' + endDate; } isIE10orLower() { - if (window.document["documentMode"]) { + if (window.document['documentMode']) { return true; } diff --git a/vsd-app/ClientApp/src/app/app.module.ts b/vsd-app/ClientApp/src/app/app.module.ts index 1561abac..beef81a8 100644 --- a/vsd-app/ClientApp/src/app/app.module.ts +++ b/vsd-app/ClientApp/src/app/app.module.ts @@ -68,7 +68,7 @@ import { JusticeApplicationDataService } from './services/justice-application-da import { LookupService } from './services/lookup.service'; import { MedicalInformationComponent } from './shared/medical-information/medical-information.component'; import { NgBusyModule } from 'ng-busy'; -import { NgxMaskModule } from 'ngx-mask' +import { NgxMaskModule } from 'ngx-mask'; import { NotFoundComponent } from './not-found/not-found.component'; import { PersonalInformationComponent } from './shared/personal-information/personal-information.component'; import { PhonePipe } from './pipes/phone.pipe'; @@ -124,7 +124,7 @@ import { MessageDialog } from './shared/dialogs/message-dialog/message.dialog'; ToolTipTriggerComponent, VictimApplicationComponent, VictimInformationComponent, - WitnessApplicationComponent, + WitnessApplicationComponent ], imports: [ AppRoutingModule, @@ -174,7 +174,7 @@ import { MessageDialog } from './shared/dialogs/message-dialog/message.dialog'; BsDatepickerModule.forRoot(), NgxMaskModule.forRoot(), TooltipModule.forRoot(), - TypeaheadModule.forRoot(), + TypeaheadModule.forRoot() ], exports: [ AppRoutingModule, @@ -218,7 +218,7 @@ import { MessageDialog } from './shared/dialogs/message-dialog/message.dialog'; MatToolbarModule, MatTooltipModule, ReactiveFormsModule, - TooltipModule, + TooltipModule ], providers: [ AEMService, @@ -228,7 +228,7 @@ import { MessageDialog } from './shared/dialogs/message-dialog/message.dialog'; LookupService, StateService, HeaderTitleService, - Title, + Title ], entryComponents: [ CancelApplicationDialog, @@ -237,8 +237,8 @@ import { MessageDialog } from './shared/dialogs/message-dialog/message.dialog'; GSTWarningDialog, MessageDialog, SignPadDialog, - SummaryOfBenefitsDialog, + SummaryOfBenefitsDialog ], bootstrap: [AppComponent] }) -export class AppModule { } +export class AppModule {} diff --git a/vsd-app/ClientApp/src/app/application-cancelled/application-cancelled.component.scss b/vsd-app/ClientApp/src/app/application-cancelled/application-cancelled.component.scss index a564fc3c..35129615 100644 --- a/vsd-app/ClientApp/src/app/application-cancelled/application-cancelled.component.scss +++ b/vsd-app/ClientApp/src/app/application-cancelled/application-cancelled.component.scss @@ -1,19 +1,19 @@ .contact-info-box { - background-color: #f1f1f2; - color: #000; - margin-top: 50px; - margin-bottom: 20px; - padding: 30px; - padding-top: 20px; + background-color: #f1f1f2; + color: #000; + margin-top: 50px; + margin-bottom: 20px; + padding: 30px; + padding-top: 20px; - h3 { - margin-top: 10px; - margin-bottom: 20px; - font-weight: 600; - } + h3 { + margin-top: 10px; + margin-bottom: 20px; + font-weight: 600; + } - p { - margin: 20px 0; - font-size: 16px; - } + p { + margin: 20px 0; + font-size: 16px; + } } diff --git a/vsd-app/ClientApp/src/app/application-cancelled/application-cancelled.component.spec.ts b/vsd-app/ClientApp/src/app/application-cancelled/application-cancelled.component.spec.ts index 6645ef18..af8f37fa 100644 --- a/vsd-app/ClientApp/src/app/application-cancelled/application-cancelled.component.spec.ts +++ b/vsd-app/ClientApp/src/app/application-cancelled/application-cancelled.component.spec.ts @@ -1,5 +1,5 @@ import { TestBed, async, ComponentFixture, ComponentFixtureAutoDetect } from '@angular/core/testing'; -import { BrowserModule, By } from "@angular/platform-browser"; +import { BrowserModule, By } from '@angular/platform-browser'; import { ApplicationCancelledComponent } from './application-cancelled.component'; let component: ApplicationCancelledComponent; @@ -10,9 +10,7 @@ describe('ApplicationCancelled component', () => { TestBed.configureTestingModule({ declarations: [ApplicationCancelledComponent], imports: [BrowserModule], - providers: [ - { provide: ComponentFixtureAutoDetect, useValue: true } - ] + providers: [{ provide: ComponentFixtureAutoDetect, useValue: true }] }); fixture = TestBed.createComponent(ApplicationCancelledComponent); component = fixture.componentInstance; diff --git a/vsd-app/ClientApp/src/app/application-cancelled/application-cancelled.component.ts b/vsd-app/ClientApp/src/app/application-cancelled/application-cancelled.component.ts index 5ce36b9f..5e9269e1 100644 --- a/vsd-app/ClientApp/src/app/application-cancelled/application-cancelled.component.ts +++ b/vsd-app/ClientApp/src/app/application-cancelled/application-cancelled.component.ts @@ -1,5 +1,5 @@ import { Component, OnInit } from '@angular/core'; -import { Router, RouterModule } from "@angular/router"; +import { Router, RouterModule } from '@angular/router'; import { ActivatedRoute } from '@angular/router'; import { LookupService } from '../services/lookup.service'; @@ -9,12 +9,11 @@ import { LookupService } from '../services/lookup.service'; styleUrls: ['./application-cancelled.component.scss'] }) export class ApplicationCancelledComponent implements OnInit { - applicationType: string; - cvapEmail: string = ""; + cvapEmail: string = ''; constructor(private router: Router, private route: ActivatedRoute, private lookupService: LookupService) { - this.router.navigateByUrl("/application-cancelled"); + this.router.navigateByUrl('/application-cancelled'); } ngOnInit() { @@ -23,8 +22,7 @@ export class ApplicationCancelledComponent implements OnInit { // this.applicationType = myData; if (this.lookupService.cvapEmail) { this.cvapEmail = this.lookupService.cvapEmail; - } - else { + } else { this.lookupService.getCVAPEmails().subscribe((res) => { this.cvapEmail = res.cvapEmail; }); diff --git a/vsd-app/ClientApp/src/app/application-success/application-success.component.scss b/vsd-app/ClientApp/src/app/application-success/application-success.component.scss index e02abfc9..5f282702 100644 --- a/vsd-app/ClientApp/src/app/application-success/application-success.component.scss +++ b/vsd-app/ClientApp/src/app/application-success/application-success.component.scss @@ -1 +1 @@ - + \ No newline at end of file diff --git a/vsd-app/ClientApp/src/app/application-success/application-success.component.spec.ts b/vsd-app/ClientApp/src/app/application-success/application-success.component.spec.ts index 256ab577..a284318d 100644 --- a/vsd-app/ClientApp/src/app/application-success/application-success.component.spec.ts +++ b/vsd-app/ClientApp/src/app/application-success/application-success.component.spec.ts @@ -1,5 +1,5 @@ import { TestBed, async, ComponentFixture, ComponentFixtureAutoDetect } from '@angular/core/testing'; -import { BrowserModule, By } from "@angular/platform-browser"; +import { BrowserModule, By } from '@angular/platform-browser'; import { ApplicationSuccessComponent } from './application-success.component'; let component: ApplicationSuccessComponent; @@ -10,9 +10,7 @@ describe('ApplicationSuccess component', () => { TestBed.configureTestingModule({ declarations: [ApplicationSuccessComponent], imports: [BrowserModule], - providers: [ - { provide: ComponentFixtureAutoDetect, useValue: true } - ] + providers: [{ provide: ComponentFixtureAutoDetect, useValue: true }] }); fixture = TestBed.createComponent(ApplicationSuccessComponent); component = fixture.componentInstance; diff --git a/vsd-app/ClientApp/src/app/application-success/application-success.component.ts b/vsd-app/ClientApp/src/app/application-success/application-success.component.ts index db75c5a7..79b7fb11 100644 --- a/vsd-app/ClientApp/src/app/application-success/application-success.component.ts +++ b/vsd-app/ClientApp/src/app/application-success/application-success.component.ts @@ -1,5 +1,5 @@ import { Component } from '@angular/core'; -import { Router } from "@angular/router"; +import { Router } from '@angular/router'; @Component({ selector: 'application-success', @@ -8,6 +8,6 @@ import { Router } from "@angular/router"; }) export class ApplicationSuccessComponent { constructor(private router: Router) { - this.router.navigateByUrl("/application-success"); - } + this.router.navigateByUrl('/application-success'); + } } diff --git a/vsd-app/ClientApp/src/app/breadcrumb/breadcrumb.component.spec.ts b/vsd-app/ClientApp/src/app/breadcrumb/breadcrumb.component.spec.ts index 7cffcadc..ee589835 100644 --- a/vsd-app/ClientApp/src/app/breadcrumb/breadcrumb.component.spec.ts +++ b/vsd-app/ClientApp/src/app/breadcrumb/breadcrumb.component.spec.ts @@ -1,7 +1,5 @@ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; -import { - RouterTestingModule -} from '@angular/router/testing'; +import { RouterTestingModule } from '@angular/router/testing'; import { RouterLink, RouterLinkWithHref } from '@angular/router'; import { BreadcrumbComponent } from './breadcrumb.component'; @@ -12,12 +10,9 @@ describe('BreadcrumbComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - declarations: [ BreadcrumbComponent ], - imports: [ RouterTestingModule ] - }) - .compileComponents(); - - + declarations: [BreadcrumbComponent], + imports: [RouterTestingModule] + }).compileComponents(); })); beforeEach(() => { diff --git a/vsd-app/ClientApp/src/app/breadcrumb/breadcrumb.component.ts b/vsd-app/ClientApp/src/app/breadcrumb/breadcrumb.component.ts index 20f96400..8ef0fe3a 100644 --- a/vsd-app/ClientApp/src/app/breadcrumb/breadcrumb.component.ts +++ b/vsd-app/ClientApp/src/app/breadcrumb/breadcrumb.component.ts @@ -2,7 +2,6 @@ import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute, NavigationEnd } from '@angular/router'; import { filter } from 'rxjs/operators'; - @Component({ selector: 'breadcrumb', templateUrl: './breadcrumb.component.html', @@ -12,35 +11,29 @@ export class BreadcrumbComponent implements OnInit { public breadcrumbs: Array<{}> = []; public visible = false; - constructor ( - private router:Router, - private route:ActivatedRoute - ) { } + constructor(private router: Router, private route: ActivatedRoute) {} ngOnInit() { const ROUTE_DATA_BREADCRUMB: string = 'breadcrumb'; const PRIMARY_OUTLET: string = 'primary'; - function resolveBreadcrumbs(route, urlPrefix : string, prevName : string) { + function resolveBreadcrumbs(route, urlPrefix: string, prevName: string) { let ret = []; let children = route.children; - if(children) { - children.forEach(child => { - + if (children) { + children.forEach((child) => { // Verify this is the primary route if (child.outlet !== PRIMARY_OUTLET) { return; } //get the route's URL segment - let routeURL: string = urlPrefix + child.snapshot.url - .map(segment => segment.path) - .join('/'); + let routeURL: string = urlPrefix + child.snapshot.url.map((segment) => segment.path).join('/'); // Verify the custom data property "breadcrumb" is specified on the route if (child.snapshot.data.hasOwnProperty(ROUTE_DATA_BREADCRUMB)) { let bcName = child.snapshot.data[ROUTE_DATA_BREADCRUMB]; - if(bcName !== null && bcName !== '' && bcName !== prevName) { + if (bcName !== null && bcName !== '' && bcName !== prevName) { ret.push({ label: child.snapshot.data[ROUTE_DATA_BREADCRUMB], url: routeURL @@ -55,12 +48,9 @@ export class BreadcrumbComponent implements OnInit { return ret; } - this.router.events - .pipe(filter( event => event instanceof NavigationEnd)) - .subscribe( event => { - this.breadcrumbs = resolveBreadcrumbs(this.route.root, '', ''); - this.visible = this.breadcrumbs.length > 0; - }) + this.router.events.pipe(filter((event) => event instanceof NavigationEnd)).subscribe((event) => { + this.breadcrumbs = resolveBreadcrumbs(this.route.root, '', ''); + this.visible = this.breadcrumbs.length > 0; + }); } - } diff --git a/vsd-app/ClientApp/src/app/home/home.component.scss b/vsd-app/ClientApp/src/app/home/home.component.scss index c8d3abef..0ffa5314 100644 --- a/vsd-app/ClientApp/src/app/home/home.component.scss +++ b/vsd-app/ClientApp/src/app/home/home.component.scss @@ -1,6 +1,6 @@ p { - font-size: 16px; - margin-bottom: 1.2em; + font-size: 16px; + margin-bottom: 1.2em; } .was-in-bc-warning { diff --git a/vsd-app/ClientApp/src/app/home/home.component.spec.ts b/vsd-app/ClientApp/src/app/home/home.component.spec.ts index 490e81bd..7e1d513d 100644 --- a/vsd-app/ClientApp/src/app/home/home.component.spec.ts +++ b/vsd-app/ClientApp/src/app/home/home.component.spec.ts @@ -8,9 +8,8 @@ describe('HomeComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - declarations: [ HomeComponent ] - }) - .compileComponents(); + declarations: [HomeComponent] + }).compileComponents(); })); beforeEach(() => { diff --git a/vsd-app/ClientApp/src/app/home/home.component.ts b/vsd-app/ClientApp/src/app/home/home.component.ts index 07d28de6..37575fff 100644 --- a/vsd-app/ClientApp/src/app/home/home.component.ts +++ b/vsd-app/ClientApp/src/app/home/home.component.ts @@ -20,18 +20,15 @@ export class HomeComponent extends FormBase implements OnInit { isLocalHost: boolean = false; isIE: boolean = false; - constructor( - private titleService: Title, - private fb: FormBuilder, - private router: Router) { + constructor(private titleService: Title, private fb: FormBuilder, private router: Router) { super(); } ngOnInit() { var ua = window.navigator.userAgent; this.isIE = /MSIE|Trident/.test(ua); - - if (window.location.origin === "http://localhost:5000") { + + if (window.location.origin === 'http://localhost:5000') { this.isLocalHost = true; } @@ -40,7 +37,7 @@ export class HomeComponent extends FormBase implements OnInit { this.form = this.fb.group({ applicationType: ['0', Validators.required], completingOnBehalfOf: ['', Validators.required], - wasCrimeInBC: ['', Validators.required], + wasCrimeInBC: ['', Validators.required] }); } @@ -101,7 +98,7 @@ export class HomeComponent extends FormBase implements OnInit { // console.log(applicationType); let navigationExtras: NavigationExtras = { - queryParams: { 'ob': behalfOf } + queryParams: { ob: behalfOf } }; this.router.navigate([routeUrl], navigationExtras); diff --git a/vsd-app/ClientApp/src/app/ifm-application/ifm-application.component.scss b/vsd-app/ClientApp/src/app/ifm-application/ifm-application.component.scss index c62175b8..14fb6d92 100644 --- a/vsd-app/ClientApp/src/app/ifm-application/ifm-application.component.scss +++ b/vsd-app/ClientApp/src/app/ifm-application/ifm-application.component.scss @@ -13,4 +13,4 @@ h2, h3 { margin-top: 30px; margin-bottom: 20px; -} \ No newline at end of file +} diff --git a/vsd-app/ClientApp/src/app/ifm-application/ifm-application.component.spec.ts b/vsd-app/ClientApp/src/app/ifm-application/ifm-application.component.spec.ts index 64f08c26..0a0f995f 100644 --- a/vsd-app/ClientApp/src/app/ifm-application/ifm-application.component.spec.ts +++ b/vsd-app/ClientApp/src/app/ifm-application/ifm-application.component.spec.ts @@ -1,24 +1,21 @@ - import { TestBed, async, ComponentFixture, ComponentFixtureAutoDetect } from '@angular/core/testing'; -import { BrowserModule, By } from "@angular/platform-browser"; +import { BrowserModule, By } from '@angular/platform-browser'; import { IfmApplicationComponent } from './ifm-application.component'; let component: IfmApplicationComponent; let fixture: ComponentFixture; describe('IfmApplication component', () => { - beforeEach(async(() => { - TestBed.configureTestingModule({ - declarations: [ IfmApplicationComponent ], - imports: [ BrowserModule ], - providers: [ - { provide: ComponentFixtureAutoDetect, useValue: true } - ] - }); - fixture = TestBed.createComponent(IfmApplicationComponent); - component = fixture.componentInstance; - })); + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [IfmApplicationComponent], + imports: [BrowserModule], + providers: [{ provide: ComponentFixtureAutoDetect, useValue: true }] + }); + fixture = TestBed.createComponent(IfmApplicationComponent); + component = fixture.componentInstance; + })); - it('should do something', async(() => { - expect(true).toEqual(true); - })); + it('should do something', async(() => { + expect(true).toEqual(true); + })); }); diff --git a/vsd-app/ClientApp/src/app/ifm-application/ifm-application.component.ts b/vsd-app/ClientApp/src/app/ifm-application/ifm-application.component.ts index ca03def2..a602db7f 100644 --- a/vsd-app/ClientApp/src/app/ifm-application/ifm-application.component.ts +++ b/vsd-app/ClientApp/src/app/ifm-application/ifm-application.component.ts @@ -1,6 +1,19 @@ import { AEMService } from '../services/aem.service'; import { ActivatedRoute, Router } from '@angular/router'; -import { Application, Introduction, PersonalInformation, CrimeInformation, MedicalInformation, ExpenseInformation, EmploymentIncomeInformation, RepresentativeInformation, DeclarationInformation, AuthorizationInformation, VictimInformation, DocumentCollectioninformation } from '../interfaces/application.interface'; +import { + Application, + Introduction, + PersonalInformation, + CrimeInformation, + MedicalInformation, + ExpenseInformation, + EmploymentIncomeInformation, + RepresentativeInformation, + DeclarationInformation, + AuthorizationInformation, + VictimInformation, + DocumentCollectioninformation +} from '../interfaces/application.interface'; import { ApplicationType, OnBehalfOf } from '../shared/enums-list'; import { AuthInfoHelper } from '../shared/authorization-information/authorization-information.helper'; import { CancelDialog } from '../shared/dialogs/cancel/cancel.dialog'; @@ -40,10 +53,9 @@ const moment = _rollupMoment || _moment; providers: [ { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }, - { provide: STEPPER_GLOBAL_OPTIONS, useValue: { showError: true } }, - ], + { provide: STEPPER_GLOBAL_OPTIONS, useValue: { showError: true } } + ] }) - export class IfmApplicationComponent extends FormBase implements OnInit { @ViewChild('stepper') ifmStepper: MatVerticalStepper; FORM_TYPE = ApplicationType.IFM_Application; @@ -79,7 +91,7 @@ export class IfmApplicationComponent extends FormBase implements OnInit { relationships: [], representativeRelationships: [], courts: [], - police_detachments: [], + police_detachments: [] }; constructor( @@ -91,7 +103,7 @@ export class IfmApplicationComponent extends FormBase implements OnInit { private dialog: MatDialog, public state: StateService, public lookupService: LookupService, - private aemService: AEMService, + private aemService: AEMService ) { super(); this.formFullyValidated = false; @@ -106,52 +118,59 @@ export class IfmApplicationComponent extends FormBase implements OnInit { if (this.state.cloning) { this.form = this.state.data; this.state.cloning = false; - } - else { + } else { this.form = this.buildApplicationForm(); } let promise_array = []; - promise_array.push(new Promise((resolve, reject) => { - this.lookupService.getCountries().subscribe((res) => { - this.lookupData.countries = res.value; - if (this.lookupData.countries) { - this.lookupData.countries.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); - } - resolve(); - }); - })); - - promise_array.push(new Promise((resolve, reject) => { - this.lookupService.getProvinces().subscribe((res) => { - this.lookupData.provinces = res.value; - if (this.lookupData.provinces) { - this.lookupData.provinces.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); - } - resolve(); - }); - })); - - promise_array.push(new Promise((resolve, reject) => { - this.lookupService.getCitiesByProvince(config.canada_crm_id, config.bc_crm_id).subscribe((res) => { - this.lookupData.cities = res.value; - if (this.lookupData.cities) { - this.lookupData.cities.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); - } - resolve(); - }); - })); - - promise_array.push(new Promise((resolve, reject) => { - this.lookupService.getRepresentativeRelationships().subscribe((res) => { - this.lookupData.representativeRelationships = res.value; - if (this.lookupData.representativeRelationships) { - this.lookupData.representativeRelationships.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); - } - resolve(); - }); - })); + promise_array.push( + new Promise((resolve, reject) => { + this.lookupService.getCountries().subscribe((res) => { + this.lookupData.countries = res.value; + if (this.lookupData.countries) { + this.lookupData.countries.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); + } + resolve(); + }); + }) + ); + + promise_array.push( + new Promise((resolve, reject) => { + this.lookupService.getProvinces().subscribe((res) => { + this.lookupData.provinces = res.value; + if (this.lookupData.provinces) { + this.lookupData.provinces.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); + } + resolve(); + }); + }) + ); + + promise_array.push( + new Promise((resolve, reject) => { + this.lookupService.getCitiesByProvince(config.canada_crm_id, config.bc_crm_id).subscribe((res) => { + this.lookupData.cities = res.value; + if (this.lookupData.cities) { + this.lookupData.cities.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); + } + resolve(); + }); + }) + ); + + promise_array.push( + new Promise((resolve, reject) => { + this.lookupService.getRepresentativeRelationships().subscribe((res) => { + this.lookupData.representativeRelationships = res.value; + if (this.lookupData.representativeRelationships) { + this.lookupData.representativeRelationships.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); + } + resolve(); + }); + }) + ); Promise.all(promise_array).then((res) => { this.didLoad = true; @@ -170,7 +189,7 @@ export class IfmApplicationComponent extends FormBase implements OnInit { let self = this; let dialogRef = this.dialog.open(CancelDialog, { autoFocus: false, - data: { type: "Application" } + data: { type: 'Application' } }); dialogRef.afterClosed().subscribe((res: any) => { @@ -185,7 +204,17 @@ export class IfmApplicationComponent extends FormBase implements OnInit { } getFormGroupName(groupIndex: any) { - let elements: Array = ['introduction', 'personalInformation', 'victimInformation', 'crimeInformation', 'medicalInformation', 'expenseInformation', 'representativeInformation', 'declarationInformation', 'authorizationInformation']; + let elements: Array = [ + 'introduction', + 'personalInformation', + 'victimInformation', + 'crimeInformation', + 'medicalInformation', + 'expenseInformation', + 'representativeInformation', + 'declarationInformation', + 'authorizationInformation' + ]; return elements[groupIndex]; } @@ -227,42 +256,51 @@ export class IfmApplicationComponent extends FormBase implements OnInit { submitApplication() { this.submitting = true; if (this.form.valid) { - this.getApplicationPDFs().then((pdfs: DocumentCollectioninformation[]) => { - let form = this.harvestForm(); - form.ApplicationPDFs = pdfs; - this.justiceDataService.submitApplication(form) - .subscribe( - data => { + this.getApplicationPDFs() + .then((pdfs: DocumentCollectioninformation[]) => { + let form = this.harvestForm(); + form.ApplicationPDFs = pdfs; + this.justiceDataService.submitApplication(form).subscribe( + (data) => { if (data['IsSuccess'] == true) { this.router.navigate(['/application-success']); - } - else { + } else { this.submitting = false; - this.snackBar.open('Error submitting application. ' + data['message'], 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); + this.snackBar.open('Error submitting application. ' + data['message'], 'Fail', { + duration: 3500, + panelClass: ['red-snackbar'] + }); console.log('Error submitting application'); if (this.isIE) { - alert("Encountered an error. Please use another browser as this may resolve the problem.") + alert('Encountered an error. Please use another browser as this may resolve the problem.'); } } }, - error => { + (error) => { this.submitting = false; - this.snackBar.open('Error submitting application', 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); + this.snackBar.open('Error submitting application', 'Fail', { + duration: 3500, + panelClass: ['red-snackbar'] + }); console.log('Error submitting application'); if (this.isIE) { - alert("Encountered an error. Please use another browser as this may resolve the problem.") + alert('Encountered an error. Please use another browser as this may resolve the problem.'); } } ); - }).catch((err) => { - this.submitting = false; - this.snackBar.open('Error submitting application. ', 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); - console.log('Error submitting application. Problem getting AEM pdfs...'); - console.log(err); - }); + }) + .catch((err) => { + this.submitting = false; + this.snackBar.open('Error submitting application. ', 'Fail', { + duration: 3500, + panelClass: ['red-snackbar'] + }); + console.log('Error submitting application. Problem getting AEM pdfs...'); + console.log(err); + }); } else { this.submitting = false; - console.log("form not validated"); + console.log('form not validated'); this.markAsTouched(); } } @@ -271,21 +309,20 @@ export class IfmApplicationComponent extends FormBase implements OnInit { this.submitting = true; if (this.form.valid) { let thisForm = _.cloneDeep(this.form); - this.getApplicationPDFs().then((pdfs: DocumentCollectioninformation[]) => { - let form = this.harvestForm(); - form.ApplicationPDFs = pdfs; - this.justiceDataService.submitApplication(form) - .subscribe( - data => { + this.getApplicationPDFs() + .then((pdfs: DocumentCollectioninformation[]) => { + let form = this.harvestForm(); + form.ApplicationPDFs = pdfs; + this.justiceDataService.submitApplication(form).subscribe( + (data) => { if (data['IsSuccess'] == true) { - if (type === "IFM") { + if (type === 'IFM') { this.submitting = false; let ifmForm = this.cloneFormToIFM(thisForm); this.ifmStepper.reset(); this.form = ifmForm; - } - else if (type === "VICTIM") { + } else if (type === 'VICTIM') { this.submitting = false; let victimForm = this.cloneFormToVictim(thisForm); @@ -294,38 +331,46 @@ export class IfmApplicationComponent extends FormBase implements OnInit { this.state.data = victimForm; this.router.navigate(['/victim-application']); - } - else { + } else { this.router.navigate(['/application-success']); } - } - else { + } else { this.submitting = false; - this.snackBar.open('Error submitting application. ' + data['message'], 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); + this.snackBar.open('Error submitting application. ' + data['message'], 'Fail', { + duration: 3500, + panelClass: ['red-snackbar'] + }); console.log('Error submitting application'); if (this.isIE) { - alert("Encountered an error. Please use another browser as this may resolve the problem.") + alert('Encountered an error. Please use another browser as this may resolve the problem.'); } } }, - error => { + (error) => { this.submitting = false; - this.snackBar.open('Error submitting application', 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); + this.snackBar.open('Error submitting application', 'Fail', { + duration: 3500, + panelClass: ['red-snackbar'] + }); console.log('Error submitting application'); if (this.isIE) { - alert("Encountered an error. Please use another browser as this may resolve the problem.") + alert('Encountered an error. Please use another browser as this may resolve the problem.'); } } ); - }).catch((err) => { - this.submitting = false; - this.snackBar.open('Error submitting application. ', 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); - console.log('Error submitting application. Problem getting AEM pdfs...'); - console.log(err); - }); + }) + .catch((err) => { + this.submitting = false; + this.snackBar.open('Error submitting application. ', 'Fail', { + duration: 3500, + panelClass: ['red-snackbar'] + }); + console.log('Error submitting application. Problem getting AEM pdfs...'); + console.log(err); + }); } else { this.submitting = false; - console.log("form not validated"); + console.log('form not validated'); this.markAsTouched(); } } @@ -344,7 +389,7 @@ export class IfmApplicationComponent extends FormBase implements OnInit { RepresentativeInformation: this.form.get('representativeInformation').value as RepresentativeInformation, DeclarationInformation: this.form.get('declarationInformation').value as DeclarationInformation, AuthorizationInformation: this.form.get('authorizationInformation').value as AuthorizationInformation, - VictimInformation: this.form.get('victimInformation').value as VictimInformation, + VictimInformation: this.form.get('victimInformation').value as VictimInformation } as Application; //using this as a workaround to collect values from disabled fields @@ -379,15 +424,15 @@ export class IfmApplicationComponent extends FormBase implements OnInit { representativeInformation: this.representativeInfoHelper.setupFormGroup(this.fb, FORM), declarationInformation: this.declarationInfoHelper.setupFormGroup(this.fb, FORM), authorizationInformation: this.authInfoHelper.setupFormGroup(this.fb, FORM), - totalAttachmentSize: [0], + totalAttachmentSize: [0] }; if (FORM === ApplicationType.IFM_Application) { - group["victimInformation"] = this.victimInfoHelper.setupFormGroupForIfmApplication(this.fb); + group['victimInformation'] = this.victimInfoHelper.setupFormGroupForIfmApplication(this.fb); } if (FORM === ApplicationType.Victim_Application) { - group["employmentIncomeInformation"] = this.employmentInfoHelper.setupFormGroup(this.fb, FORM); + group['employmentIncomeInformation'] = this.employmentInfoHelper.setupFormGroup(this.fb, FORM); } return this.fb.group(group); @@ -395,7 +440,7 @@ export class IfmApplicationComponent extends FormBase implements OnInit { @HostListener('window:afterprint') onafterprint() { - document.querySelectorAll(".slide-close")[0].classList.remove("hide-for-print") + document.querySelectorAll('.slide-close')[0].classList.remove('hide-for-print'); window.scroll(0, 0); this.showPrintView = false; } @@ -403,56 +448,63 @@ export class IfmApplicationComponent extends FormBase implements OnInit { printApplication() { window.scroll(0, 0); this.showPrintView = true; - document.querySelectorAll(".slide-close")[0].classList.add("hide-for-print"); + document.querySelectorAll('.slide-close')[0].classList.add('hide-for-print'); setTimeout(() => { window.print(); }, 100); } downloadPDF() { - this.getAEMPDF().then((pdf: string) => { - let downloadLink = document.createElement("a"); - downloadLink.href = "data:application/pdf;base64," + pdf; - downloadLink.download = "IFM-Application.pdf"; - downloadLink.target = "_blank"; - - document.body.appendChild(downloadLink); - downloadLink.click(); - document.body.removeChild(downloadLink); - }).catch((err) => { - console.log("error getting pdf"); - console.log(err); - }); + this.getAEMPDF() + .then((pdf: string) => { + let downloadLink = document.createElement('a'); + downloadLink.href = 'data:application/pdf;base64,' + pdf; + downloadLink.download = 'IFM-Application.pdf'; + downloadLink.target = '_blank'; + + document.body.appendChild(downloadLink); + downloadLink.click(); + document.body.removeChild(downloadLink); + }) + .catch((err) => { + console.log('error getting pdf'); + console.log(err); + }); } getAEMPDF(): Promise { return new Promise((resolve, reject) => { let application: Application = _.cloneDeep(this.harvestForm()); //sending large document info to aem causes it to crap out - it's also unnecessary info, so let's not send it! - application.CrimeInformation.documents.forEach(doc => doc.body = ""); - application.RepresentativeInformation.documents.forEach(doc => doc.body = ""); + application.CrimeInformation.documents.forEach((doc) => (doc.body = '')); + application.RepresentativeInformation.documents.forEach((doc) => (doc.body = '')); //full name display option for single fields - application.PersonalInformation.fullName = application.PersonalInformation.firstName + " " + application.PersonalInformation.lastName; + application.PersonalInformation.fullName = + application.PersonalInformation.firstName + ' ' + application.PersonalInformation.lastName; //display all locations as a single comma separated string - application.CrimeInformation.crimeLocations[0].location = application.CrimeInformation.crimeLocations.map(a => a.location).join(', '); + application.CrimeInformation.crimeLocations[0].location = application.CrimeInformation.crimeLocations + .map((a) => a.location) + .join(', '); //for on behalf of, if you chose parent, pdf format doesn't match webform, so relationship workaround if (application.RepresentativeInformation.completingOnBehalfOf == OnBehalfOf.Parent) { - application.RepresentativeInformation.relationshipToPersonParent = application.RepresentativeInformation.relationshipToPerson; - application.RepresentativeInformation.relationshipToPerson = ""; + application.RepresentativeInformation.relationshipToPersonParent = + application.RepresentativeInformation.relationshipToPerson; + application.RepresentativeInformation.relationshipToPerson = ''; } - this.aemService.getIFMApplicationPDF(application).subscribe((res: any) => { - console.log(res); - if (res.responseMessage) { - resolve(res.responseMessage); - } - else { - reject(res); - } - }, + this.aemService.getIFMApplicationPDF(application).subscribe( + (res: any) => { + console.log(res); + if (res.responseMessage) { + resolve(res.responseMessage); + } else { + reject(res); + } + }, (err) => { reject(err); console.log(err); - }); + } + ); }); } @@ -460,23 +512,25 @@ export class IfmApplicationComponent extends FormBase implements OnInit { return new Promise((resolve, reject) => { let application: Application = _.cloneDeep(this.harvestForm()); //sending large document info to aem causes it to crap out - it's also unnecessary info, so let's not send it! - application.CrimeInformation.documents.forEach(doc => doc.body = ""); - application.RepresentativeInformation.documents.forEach(doc => doc.body = ""); + application.CrimeInformation.documents.forEach((doc) => (doc.body = '')); + application.RepresentativeInformation.documents.forEach((doc) => (doc.body = '')); //full name display option for single fields - application.PersonalInformation.fullName = application.PersonalInformation.firstName + " " + application.PersonalInformation.lastName; - this.aemService.getAuthorizationPDF(application).subscribe((res: any) => { - console.log(res); - if (res.responseMessage) { - resolve(res.responseMessage); - } - else { - reject(res); - } - }, + application.PersonalInformation.fullName = + application.PersonalInformation.firstName + ' ' + application.PersonalInformation.lastName; + this.aemService.getAuthorizationPDF(application).subscribe( + (res: any) => { + console.log(res); + if (res.responseMessage) { + resolve(res.responseMessage); + } else { + reject(res); + } + }, (err) => { reject(err); console.log(err); - }); + } + ); }); } @@ -485,40 +539,50 @@ export class IfmApplicationComponent extends FormBase implements OnInit { let ret: DocumentCollectioninformation[] = []; let promise_array = []; - promise_array.push(new Promise((resolve, reject) => { - this.getAEMPDF().then((pdf: string) => { - ret.push({ - body: pdf, - filename: "IFM-Application.pdf", - subject: "", - }); - resolve(); - }).catch((err) => { - console.log(err); - reject(); - }); - })); - - promise_array.push(new Promise((resolve, reject) => { - this.getAuthPDF().then((auth_pdf: string) => { - ret.push({ - body: auth_pdf, - filename: "Authorization Form.pdf", - subject: "", - }); - resolve(); - }).catch((err) => { + promise_array.push( + new Promise((resolve, reject) => { + this.getAEMPDF() + .then((pdf: string) => { + ret.push({ + body: pdf, + filename: 'IFM-Application.pdf', + subject: '' + }); + resolve(); + }) + .catch((err) => { + console.log(err); + reject(); + }); + }) + ); + + promise_array.push( + new Promise((resolve, reject) => { + this.getAuthPDF() + .then((auth_pdf: string) => { + ret.push({ + body: auth_pdf, + filename: 'Authorization Form.pdf', + subject: '' + }); + resolve(); + }) + .catch((err) => { + console.log(err); + reject(); + }); + }) + ); + + Promise.all(promise_array) + .then((res) => { + resolve(ret); + }) + .catch((err) => { console.log(err); - reject(); + reject(err); }); - })); - - Promise.all(promise_array).then((res) => { - resolve(ret); - }).catch((err) => { - console.log(err); - reject(err); - }); }); } @@ -564,7 +628,10 @@ export class IfmApplicationComponent extends FormBase implements OnInit { ret.get('crimeInformation').get('offenderRelationship').patchValue(''); ret.get('crimeInformation').get('haveYouSuedOffender').patchValue(0); ret.get('crimeInformation').get('intendToSueOffender').patchValue(null); - ret.get('crimeInformation').get('racafInformation').patchValue(this.crimeInfoHelper.createRACAFInformation(this.fb).value); + ret + .get('crimeInformation') + .get('racafInformation') + .patchValue(this.crimeInfoHelper.createRACAFInformation(this.fb).value); let authorizedPersonsLength = currentForm.get('authorizationInformation').get('authorizedPerson').value.length; let authorizedPersons = ret.get('authorizationInformation').get('authorizedPerson') as FormArray; @@ -608,7 +675,6 @@ export class IfmApplicationComponent extends FormBase implements OnInit { ret.get('personalInformation').get('agreeToCvapCommunicationExchange').patchValue(''); ret.get('personalInformation').get('leaveVoicemail').patchValue(0); - ret.get('victimInformation').patchValue(currentForm.get('victimInformation').value); let crimeLocationsLength = currentForm.get('crimeInformation').get('crimeLocations').value.length; let crimeLocations = ret.get('crimeInformation').get('crimeLocations') as FormArray; @@ -627,7 +693,10 @@ export class IfmApplicationComponent extends FormBase implements OnInit { ret.get('crimeInformation').get('offenderRelationship').patchValue(''); ret.get('crimeInformation').get('haveYouSuedOffender').patchValue(0); ret.get('crimeInformation').get('intendToSueOffender').patchValue(null); - ret.get('crimeInformation').get('racafInformation').patchValue(this.crimeInfoHelper.createRACAFInformation(this.fb).value); + ret + .get('crimeInformation') + .get('racafInformation') + .patchValue(this.crimeInfoHelper.createRACAFInformation(this.fb).value); let authorizedPersonsLength = currentForm.get('authorizationInformation').get('authorizedPerson').value.length; let authorizedPersons = ret.get('authorizationInformation').get('authorizedPerson') as FormArray; diff --git a/vsd-app/ClientApp/src/app/interfaces/application.interface.ts b/vsd-app/ClientApp/src/app/interfaces/application.interface.ts index a5f5dce0..a0004621 100644 --- a/vsd-app/ClientApp/src/app/interfaces/application.interface.ts +++ b/vsd-app/ClientApp/src/app/interfaces/application.interface.ts @@ -1,5 +1,5 @@ -import { Address } from "./address.interface"; -import { Courtfile } from "./files.interface"; +import { Address } from './address.interface'; +import { Courtfile } from './files.interface'; export interface Application { ApplicationType: number; diff --git a/vsd-app/ClientApp/src/app/interfaces/counsellor-invoice.interface.ts b/vsd-app/ClientApp/src/app/interfaces/counsellor-invoice.interface.ts index 0695b531..8b63fdf5 100644 --- a/vsd-app/ClientApp/src/app/interfaces/counsellor-invoice.interface.ts +++ b/vsd-app/ClientApp/src/app/interfaces/counsellor-invoice.interface.ts @@ -1,13 +1,13 @@ -import { DocumentCollectioninformation } from "./application.interface"; +import { DocumentCollectioninformation } from './application.interface'; export interface CounsellorInvoice { InvoiceDetails: InvoiceDetails; DocumentCollection: DocumentCollectioninformation[]; } export interface InvoiceDetails { - registeredCounsellorWithCvap: boolean; // Not used in transfer to Dynamics - doYouHaveCvapCounsellorNumber: boolean; // Not used in transfer to Dynamics - doYouHaveVendorNumberOnFile: boolean; // Not used in transfer to Dynamics + registeredCounsellorWithCvap: boolean; // Not used in transfer to Dynamics + doYouHaveCvapCounsellorNumber: boolean; // Not used in transfer to Dynamics + doYouHaveVendorNumberOnFile: boolean; // Not used in transfer to Dynamics counsellorRegistrationNumber: string; counsellorLastName: string; vendorNumber: string; @@ -23,13 +23,13 @@ export interface InvoiceDetails { exemptFromGst: boolean; gstApplicable: boolean; lineItems: LineItem[]; - declaredAndSigned: boolean; // Not used in transfer to Dynamics + declaredAndSigned: boolean; // Not used in transfer to Dynamics } export interface LineItem { counsellingType: number; counsellingTypeName?: string; sessionDate: Date; sessionHours: number; - sessionAmount: number; // Not used in transfer to Dynamics + sessionAmount: number; // Not used in transfer to Dynamics missedSession: boolean; } diff --git a/vsd-app/ClientApp/src/app/interfaces/dynamics/crm-restitution.ts b/vsd-app/ClientApp/src/app/interfaces/dynamics/crm-restitution.ts index 7265e875..99f5dccf 100644 --- a/vsd-app/ClientApp/src/app/interfaces/dynamics/crm-restitution.ts +++ b/vsd-app/ClientApp/src/app/interfaces/dynamics/crm-restitution.ts @@ -1,63 +1,63 @@ export interface iRestitutionCRM { - Application: iCRMApplication; - CourtInfoCollection?: iCRMCourtInfo[]; - DocumentCollection?: iCRMDocument[]; - ProviderCollection?: iCRMParticipant[]; + Application: iCRMApplication; + CourtInfoCollection?: iCRMCourtInfo[]; + DocumentCollection?: iCRMDocument[]; + ProviderCollection?: iCRMParticipant[]; } export interface iCRMApplication { - vsd_applicanttype: number; - vsd_applicantsfirstname: string; - vsd_applicantsmiddlename: string; - vsd_applicantslastname: string; - vsd_otherfirstname?: string; - vsd_otherlastname?: string; - vsd_applicantsgendercode: number; - vsd_applicantsbirthdate: Date; - vsd_indigenous: number; - vsd_applicantspreferredmethodofcontact: number; - vsd_smspreferred?: number; - vsd_applicantsprimaryphonenumber?: string; - vsd_applicantsalternatephonenumber?: string; - vsd_applicantsemail?: string; - vsd_applicantsprimaryaddressline1: string; - vsd_applicantsprimaryaddressline2: string; - vsd_applicantsprimarycity: string; - vsd_applicantsprimaryprovince: string; - vsd_applicantsprimarypostalcode: string; - vsd_applicantsprimarycountry: string; - vsd_voicemailoption?: number; - vsd_applicantssignature: string; + vsd_applicanttype: number; + vsd_applicantsfirstname: string; + vsd_applicantsmiddlename: string; + vsd_applicantslastname: string; + vsd_otherfirstname?: string; + vsd_otherlastname?: string; + vsd_applicantsgendercode: number; + vsd_applicantsbirthdate: Date; + vsd_indigenous: number; + vsd_applicantspreferredmethodofcontact: number; + vsd_smspreferred?: number; + vsd_applicantsprimaryphonenumber?: string; + vsd_applicantsalternatephonenumber?: string; + vsd_applicantsemail?: string; + vsd_applicantsprimaryaddressline1: string; + vsd_applicantsprimaryaddressline2: string; + vsd_applicantsprimarycity: string; + vsd_applicantsprimaryprovince: string; + vsd_applicantsprimarypostalcode: string; + vsd_applicantsprimarycountry: string; + vsd_voicemailoption?: number; + vsd_applicantssignature: string; } export interface iCRMCourtInfo { - vsd_courtfilenumber: string; - vsd_courtlocation: string; + vsd_courtfilenumber: string; + vsd_courtlocation: string; } export interface iCRMParticipant { - vsd_firstname?: string; - vsd_middlename?: string; - vsd_lastname?: string; - vsd_preferredname?: string; - vsd_companyname?: string; - vsd_name?: string; - vsd_addressline1?: string; - vsd_addressline2?: string; - vsd_city?: string; - vsd_province?: string; - vsd_postalcode?: string; - vsd_country?: string; - vsd_preferredmethodofcontact?: number; - vsd_restcontactpreferenceforupdates?: number; - vsd_phonenumber?: string; - vsd_alternatephonenumber?: string; - vsd_voicemailoptions?: number; - vsd_email?: string; - vsd_rest_custodylocation?: string; - vsd_rest_programname?: string; - vsd_relationship1: string; - vsd_relationship2?: string; + vsd_firstname?: string; + vsd_middlename?: string; + vsd_lastname?: string; + vsd_preferredname?: string; + vsd_companyname?: string; + vsd_name?: string; + vsd_addressline1?: string; + vsd_addressline2?: string; + vsd_city?: string; + vsd_province?: string; + vsd_postalcode?: string; + vsd_country?: string; + vsd_preferredmethodofcontact?: number; + vsd_restcontactpreferenceforupdates?: number; + vsd_phonenumber?: string; + vsd_alternatephonenumber?: string; + vsd_voicemailoptions?: number; + vsd_email?: string; + vsd_rest_custodylocation?: string; + vsd_rest_programname?: string; + vsd_relationship1: string; + vsd_relationship2?: string; } export interface iCRMDocument { - filename: string; - body: string; - subject?: string; -} \ No newline at end of file + filename: string; + body: string; + subject?: string; +} diff --git a/vsd-app/ClientApp/src/app/interfaces/files.interface.ts b/vsd-app/ClientApp/src/app/interfaces/files.interface.ts index b127af69..7498be35 100644 --- a/vsd-app/ClientApp/src/app/interfaces/files.interface.ts +++ b/vsd-app/ClientApp/src/app/interfaces/files.interface.ts @@ -10,4 +10,3 @@ export interface UploadFile { body: string; fileName: string; } - diff --git a/vsd-app/ClientApp/src/app/interfaces/lookup-data.interface.ts b/vsd-app/ClientApp/src/app/interfaces/lookup-data.interface.ts index 11c3533c..78d95e1b 100644 --- a/vsd-app/ClientApp/src/app/interfaces/lookup-data.interface.ts +++ b/vsd-app/ClientApp/src/app/interfaces/lookup-data.interface.ts @@ -1,54 +1,52 @@ export interface iLookupData { - countries: iCountry[]; - provinces: iProvince[]; - cities: iCity[]; - relationships?: iRelationship[]; - imfRepresentativeRelationships?: iRelationship[]; - representativeRelationships?: iRelationship[]; - courts?: iCourt[]; - police_detachments?: iPoliceDetachment[]; + countries: iCountry[]; + provinces: iProvince[]; + cities: iCity[]; + relationships?: iRelationship[]; + imfRepresentativeRelationships?: iRelationship[]; + representativeRelationships?: iRelationship[]; + courts?: iCourt[]; + police_detachments?: iPoliceDetachment[]; } export interface iCountry { - vsd_name: string; - vsd_countryid: string; + vsd_name: string; + vsd_countryid: string; } export interface iProvince { - vsd_code: string; - _vsd_countryid_value: string; - vsd_name: string; - vsd_provinceid: string; + vsd_code: string; + _vsd_countryid_value: string; + vsd_name: string; + vsd_provinceid: string; } export interface CitiesSearchResponse { - Result: string; - CityCollection: iCity[]; - CountryCollection: iCountry[]; - ProvinceCollection: iProvince[]; + Result: string; + CityCollection: iCity[]; + CountryCollection: iCountry[]; + ProvinceCollection: iProvince[]; } - export interface iCity { - _vsd_countryid_value: string; - vsd_name: string; - _vsd_stateid_value: string; - vsd_cityid: string; + _vsd_countryid_value: string; + vsd_name: string; + _vsd_stateid_value: string; + vsd_cityid: string; } export interface iRelationship { - vsd_name: string; - vsd_relationshipid: string; - vsd_cvap_representativerelationship_imf_only?: boolean; - + vsd_name: string; + vsd_relationshipid: string; + vsd_cvap_representativerelationship_imf_only?: boolean; } export interface iCourt { - vsd_name: string; - vsd_courtid: string; + vsd_name: string; + vsd_courtid: string; } export interface iPoliceDetachment { - vsd_name: string; - vsd_policedetachmentid: string; + vsd_name: string; + vsd_policedetachmentid: string; } diff --git a/vsd-app/ClientApp/src/app/interfaces/restitution.interface.ts b/vsd-app/ClientApp/src/app/interfaces/restitution.interface.ts index 34cd5937..1a8eff37 100644 --- a/vsd-app/ClientApp/src/app/interfaces/restitution.interface.ts +++ b/vsd-app/ClientApp/src/app/interfaces/restitution.interface.ts @@ -1,5 +1,5 @@ -import { IOptionSetVal } from "../shared/enums-list"; -import { Address } from "./address.interface"; +import { IOptionSetVal } from '../shared/enums-list'; +import { Address } from './address.interface'; export interface iRestitutionApplication { ApplicationType: IOptionSetVal; @@ -68,4 +68,4 @@ export interface iDocument { filename: string; body: string; subject?: string; -} \ No newline at end of file +} diff --git a/vsd-app/ClientApp/src/app/interfaces/victim-restitution.interface.ts b/vsd-app/ClientApp/src/app/interfaces/victim-restitution.interface.ts index 5bd21d2c..343bafb3 100644 --- a/vsd-app/ClientApp/src/app/interfaces/victim-restitution.interface.ts +++ b/vsd-app/ClientApp/src/app/interfaces/victim-restitution.interface.ts @@ -1,6 +1,6 @@ -import { Address } from "./address.interface"; -import { DocumentCollectioninformation } from "./application.interface"; -import { Courtfile, ProviderFile } from "./files.interface"; +import { Address } from './address.interface'; +import { DocumentCollectioninformation } from './application.interface'; +import { Courtfile, ProviderFile } from './files.interface'; export interface VictimRestitution { RestitutionInformation: VictimRestitutionInformation; @@ -43,7 +43,4 @@ export interface VictimRestitutionInformation { declaredAndSigned: boolean; signature: string; - } - - diff --git a/vsd-app/ClientApp/src/app/not-found/not-found.component.scss b/vsd-app/ClientApp/src/app/not-found/not-found.component.scss index e02abfc9..5f282702 100644 --- a/vsd-app/ClientApp/src/app/not-found/not-found.component.scss +++ b/vsd-app/ClientApp/src/app/not-found/not-found.component.scss @@ -1 +1 @@ - + \ No newline at end of file diff --git a/vsd-app/ClientApp/src/app/not-found/not-found.component.spec.ts b/vsd-app/ClientApp/src/app/not-found/not-found.component.spec.ts index d36fd78c..2fd7aafa 100644 --- a/vsd-app/ClientApp/src/app/not-found/not-found.component.spec.ts +++ b/vsd-app/ClientApp/src/app/not-found/not-found.component.spec.ts @@ -1,25 +1,22 @@ - import { TestBed, async, ComponentFixture, ComponentFixtureAutoDetect } from '@angular/core/testing'; -import { BrowserModule, By } from "@angular/platform-browser"; +import { BrowserModule, By } from '@angular/platform-browser'; import { NotFoundComponent } from './not-found.component'; let component: NotFoundComponent; let fixture: ComponentFixture; describe('NotFound component', () => { - beforeEach(async(() => { - TestBed.configureTestingModule({ - declarations: [ NotFoundComponent ], - imports: [ BrowserModule ], - providers: [ - { provide: ComponentFixtureAutoDetect, useValue: true } - ] - }); - fixture = TestBed.createComponent(NotFoundComponent); - component = fixture.componentInstance; - })); + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [NotFoundComponent], + imports: [BrowserModule], + providers: [{ provide: ComponentFixtureAutoDetect, useValue: true }] + }); + fixture = TestBed.createComponent(NotFoundComponent); + component = fixture.componentInstance; + })); - it('should do something', async(() => { - expect(true).toEqual(true); - })); + it('should do something', async(() => { + expect(true).toEqual(true); + })); }); diff --git a/vsd-app/ClientApp/src/app/not-found/not-found.component.ts b/vsd-app/ClientApp/src/app/not-found/not-found.component.ts index 103da84c..830626b7 100644 --- a/vsd-app/ClientApp/src/app/not-found/not-found.component.ts +++ b/vsd-app/ClientApp/src/app/not-found/not-found.component.ts @@ -1,16 +1,15 @@ import { Component } from '@angular/core'; -import { Router } from "@angular/router"; +import { Router } from '@angular/router'; @Component({ - selector: 'app-not-found', - templateUrl: './not-found.component.html', - styleUrls: ['./not-found.component.scss'] + selector: 'app-not-found', + templateUrl: './not-found.component.html', + styleUrls: ['./not-found.component.scss'] }) /** NotFound component*/ export class NotFoundComponent { - /** NotFound ctor */ + /** NotFound ctor */ constructor(private router: Router) { - this.router.navigateByUrl("/404"); - - } + this.router.navigateByUrl('/404'); + } } diff --git a/vsd-app/ClientApp/src/app/pipes/phone.pipe.ts b/vsd-app/ClientApp/src/app/pipes/phone.pipe.ts index dba5c6f9..43ac8e29 100644 --- a/vsd-app/ClientApp/src/app/pipes/phone.pipe.ts +++ b/vsd-app/ClientApp/src/app/pipes/phone.pipe.ts @@ -1,13 +1,12 @@ -import { Pipe } from "@angular/core"; +import { Pipe } from '@angular/core'; @Pipe({ - name: "phone" + name: 'phone' }) export class PhonePipe { - transform(rawNum: string) { - if (rawNum && rawNum.length >= 6) - return "(" + rawNum.slice(0, 3) + ") " + rawNum.slice(3, 6) + "-" + rawNum.slice(6); - else - return rawNum; - } -} \ No newline at end of file + transform(rawNum: string) { + if (rawNum && rawNum.length >= 6) + return '(' + rawNum.slice(0, 3) + ') ' + rawNum.slice(3, 6) + '-' + rawNum.slice(6); + else return rawNum; + } +} diff --git a/vsd-app/ClientApp/src/app/quick-exit/quick-exit.component.ts b/vsd-app/ClientApp/src/app/quick-exit/quick-exit.component.ts index 8b597980..d9a380fd 100644 --- a/vsd-app/ClientApp/src/app/quick-exit/quick-exit.component.ts +++ b/vsd-app/ClientApp/src/app/quick-exit/quick-exit.component.ts @@ -8,27 +8,27 @@ import { DOCUMENT } from '@angular/common'; styleUrls: ['./quick-exit.component.scss'], animations: [ trigger('openClose', [ - state('open', style({ - transform: 'translateX(0)', - })), - state('closed', style({ - transform: 'translateX(-240px)', - })), - transition('open => closed', [ - animate('1s') - ]), - transition('closed => open', [ - animate('0.5s') - ]), - ]), - ], + state( + 'open', + style({ + transform: 'translateX(0)' + }) + ), + state( + 'closed', + style({ + transform: 'translateX(-240px)' + }) + ), + transition('open => closed', [animate('1s')]), + transition('closed => open', [animate('0.5s')]) + ]) + ] }) export class QuickExitComponent implements OnInit { isOpen = true; - constructor(@Inject(DOCUMENT) private document: any) { - - } + constructor(@Inject(DOCUMENT) private document: any) {} ngOnInit() { setTimeout(() => { diff --git a/vsd-app/ClientApp/src/app/services/aem.service.ts b/vsd-app/ClientApp/src/app/services/aem.service.ts index d412f118..d64b3a18 100644 --- a/vsd-app/ClientApp/src/app/services/aem.service.ts +++ b/vsd-app/ClientApp/src/app/services/aem.service.ts @@ -8,61 +8,56 @@ import { environment } from '../../environments/environment'; @Injectable() export class AEMService { - baseUrl = environment.apiRootUrl; - apiPath = this.baseUrl.concat('api/AEM'); - - headers: HttpHeaders = new HttpHeaders({ - 'Content-Type': 'application/json' - }); - - constructor(private http: HttpClient) { } - - public getVictimApplicationPDF(application: Application) { - return this.http.post(this.apiPath + '/victim', application, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); - } - - public getIFMApplicationPDF(application: Application) { - return this.http.post(this.apiPath + '/ifm', application, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); - } - - public getWitnessApplicationPDF(application: Application) { - return this.http.post(this.apiPath + '/witness', application, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); - } - - public getAuthorizationPDF(application: Application) { - return this.http.post(this.apiPath + '/authorization', application, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); - } - - public getInvoicePDF(invoice: CounsellorInvoice) { - return this.http.post(this.apiPath + '/invoice', invoice, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); - } - - protected handleError(err): Observable { - let errorMessage = ''; - console.log(err); - if (err.error instanceof ErrorEvent) { - // A client-side or network error occurred. Handle it accordingly. - errorMessage = err.error.message; - } else { - // The backend returned an unsuccessful response code. - // The response body may contain clues as to what went wrong, - errorMessage = `Backend returned code ${err.status}, body was: ${JSON.stringify(err.error)}`; - } - return throwError(errorMessage); + baseUrl = environment.apiRootUrl; + apiPath = this.baseUrl.concat('api/AEM'); + + headers: HttpHeaders = new HttpHeaders({ + 'Content-Type': 'application/json' + }); + + constructor(private http: HttpClient) {} + + public getVictimApplicationPDF(application: Application) { + return this.http + .post(this.apiPath + '/victim', application, { headers: this.headers }) + .pipe(retry(3), catchError(this.handleError)); + } + + public getIFMApplicationPDF(application: Application) { + return this.http + .post(this.apiPath + '/ifm', application, { headers: this.headers }) + .pipe(retry(3), catchError(this.handleError)); + } + + public getWitnessApplicationPDF(application: Application) { + return this.http + .post(this.apiPath + '/witness', application, { headers: this.headers }) + .pipe(retry(3), catchError(this.handleError)); + } + + public getAuthorizationPDF(application: Application) { + return this.http + .post(this.apiPath + '/authorization', application, { headers: this.headers }) + .pipe(retry(3), catchError(this.handleError)); + } + + public getInvoicePDF(invoice: CounsellorInvoice) { + return this.http + .post(this.apiPath + '/invoice', invoice, { headers: this.headers }) + .pipe(retry(3), catchError(this.handleError)); + } + + protected handleError(err): Observable { + let errorMessage = ''; + console.log(err); + if (err.error instanceof ErrorEvent) { + // A client-side or network error occurred. Handle it accordingly. + errorMessage = err.error.message; + } else { + // The backend returned an unsuccessful response code. + // The response body may contain clues as to what went wrong, + errorMessage = `Backend returned code ${err.status}, body was: ${JSON.stringify(err.error)}`; } + return throwError(errorMessage); + } } diff --git a/vsd-app/ClientApp/src/app/services/config.service.ts b/vsd-app/ClientApp/src/app/services/config.service.ts index 837e54bb..bcd820e7 100644 --- a/vsd-app/ClientApp/src/app/services/config.service.ts +++ b/vsd-app/ClientApp/src/app/services/config.service.ts @@ -3,27 +3,26 @@ import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { Configuration } from '../interfaces/configuration.interface'; -import {environment} from "../../environments/environment"; +import { environment } from '../../environments/environment'; @Injectable({ providedIn: 'root' }) -export class ConfigService{ +export class ConfigService { headers: HttpHeaders = new HttpHeaders({ 'Content-Type': 'application/json' }); baseUrl = environment.apiRootUrl; apiPath = this.baseUrl.concat('api/Configuration'); - constructor( - private http: HttpClient, - ) { } + constructor(private http: HttpClient) {} public async load(): Promise { try { - return await - this.http.get(this.apiPath, { headers: this.headers }) - .pipe(catchError(this.handleError)).toPromise(); + return await this.http + .get(this.apiPath, { headers: this.headers }) + .pipe(catchError(this.handleError)) + .toPromise(); } catch (error) { this.handleError(error); throw error; diff --git a/vsd-app/ClientApp/src/app/services/justice-application-data.service.ts b/vsd-app/ClientApp/src/app/services/justice-application-data.service.ts index 3c0bbef6..1646d72e 100644 --- a/vsd-app/ClientApp/src/app/services/justice-application-data.service.ts +++ b/vsd-app/ClientApp/src/app/services/justice-application-data.service.ts @@ -10,13 +10,13 @@ export class JusticeApplicationDataService { apiPath = this.baseUrl.concat('api/justice/'); pdfHeaders: HttpHeaders = new HttpHeaders({ - 'Content-Type': 'application/json;charset=UTF-8', + 'Content-Type': 'application/json;charset=UTF-8' }); headers: HttpHeaders = new HttpHeaders({ 'Content-Type': 'application/json' }); - constructor(private http: HttpClient) { } + constructor(private http: HttpClient) {} public submitApplication(application: Application) { return this.http.post(this.apiPath + 'saveapplication', application, { headers: this.headers }); @@ -39,9 +39,14 @@ export class JusticeApplicationDataService { // } public validateVendor(vendorNumber, vendorPostalCode) { - return this.http.get(`${this.apiPath}validate_vendor/${vendorNumber}/${vendorPostalCode}`, { headers: this.headers }); + return this.http.get(`${this.apiPath}validate_vendor/${vendorNumber}/${vendorPostalCode}`, { + headers: this.headers + }); } public validateVendorAndCounsellor(vendorNumber, vendorPostalCode, counsellorNumber, counsellorLastName) { - return this.http.get(`${this.apiPath}validate_vendor_and_counsellor/${vendorNumber}/${vendorPostalCode}/${counsellorNumber}/${counsellorLastName}`, { headers: this.headers }); + return this.http.get( + `${this.apiPath}validate_vendor_and_counsellor/${vendorNumber}/${vendorPostalCode}/${counsellorNumber}/${counsellorLastName}`, + { headers: this.headers } + ); } } diff --git a/vsd-app/ClientApp/src/app/services/lookup.service.ts b/vsd-app/ClientApp/src/app/services/lookup.service.ts index f5810533..9c317fef 100644 --- a/vsd-app/ClientApp/src/app/services/lookup.service.ts +++ b/vsd-app/ClientApp/src/app/services/lookup.service.ts @@ -4,7 +4,6 @@ import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { environment } from '../../environments/environment'; - @Injectable({ providedIn: 'root' }) @@ -13,114 +12,99 @@ export class LookupService { baseUrl = environment.apiRootUrl; apiPath = this.baseUrl.concat('api/Lookup'); - cvapEmail: string = ""; - cvapCounsellingEmail: string = ""; + cvapEmail: string = ''; + cvapCounsellingEmail: string = ''; - constructor( - private http: HttpClient, - ) { } + constructor(private http: HttpClient) {} getCVAPEmails(): Observable { - return this.http.get(`${this.apiPath}/cvap-emails`, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); + return this.http + .get(`${this.apiPath}/cvap-emails`, { headers: this.headers }) + .pipe(retry(3), catchError(this.handleError)); } getCountries(): Observable { - return this.http.get(`${this.apiPath}/countries`, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); + return this.http + .get(`${this.apiPath}/countries`, { headers: this.headers }) + .pipe(retry(3), catchError(this.handleError)); } getProvinces(): Observable { - return this.http.get(`${this.apiPath}/provinces`, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); + return this.http + .get(`${this.apiPath}/provinces`, { headers: this.headers }) + .pipe(retry(3), catchError(this.handleError)); } getCities(): Observable { - return this.http.get(`${this.apiPath}/cities`, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); + return this.http + .get(`${this.apiPath}/cities`, { headers: this.headers }) + .pipe(retry(3), catchError(this.handleError)); } searchCities(country: string, province: string, searchVal: string): Observable { let limit = 15; - return this.http.get(`${this.apiPath}/cities/search?country=${country}&province=${province}&searchVal=${searchVal}&limit=${limit}`, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); + return this.http + .get( + `${this.apiPath}/cities/search?country=${country}&province=${province}&searchVal=${searchVal}&limit=${limit}`, + { headers: this.headers } + ) + .pipe(retry(3), catchError(this.handleError)); } - getCitiesByCountry(country_id: string): Observable { - return this.http.get(`${this.apiPath}/country/${country_id}/cities`, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); + return this.http + .get(`${this.apiPath}/country/${country_id}/cities`, { headers: this.headers }) + .pipe(retry(3), catchError(this.handleError)); } getCitiesByProvince(country_id: string, province_id: string): Observable { - return this.http.get(`${this.apiPath}/country/${country_id}/province/${province_id}/cities`, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); + return this.http + .get(`${this.apiPath}/country/${country_id}/province/${province_id}/cities`, { headers: this.headers }) + .pipe(retry(3), catchError(this.handleError)); } getRelationships(): Observable { - return this.http.get(`${this.apiPath}/relationships`, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); + return this.http + .get(`${this.apiPath}/relationships`, { headers: this.headers }) + .pipe(retry(3), catchError(this.handleError)); } getOptionalAuthorizationRelationships(): Observable { - return this.http.get(`${this.apiPath}/auth_relationships`, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); + return this.http + .get(`${this.apiPath}/auth_relationships`, { headers: this.headers }) + .pipe(retry(3), catchError(this.handleError)); } getRepresentativeRelationships(): Observable { - return this.http.get(`${this.apiPath}/representative_relationships`, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); + return this.http + .get(`${this.apiPath}/representative_relationships`, { headers: this.headers }) + .pipe(retry(3), catchError(this.handleError)); } - getIMFRepresentativeRelationships(): Observable { - return this.http.get(`${this.apiPath}/imf_representative_relationships`, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); + getIMFRepresentativeRelationships(): Observable { + return this.http + .get(`${this.apiPath}/imf_representative_relationships`, { headers: this.headers }) + .pipe(retry(3), catchError(this.handleError)); } getRestitutionRelationships(): Observable { - return this.http.get(`${this.apiPath}/restitution_relationships`, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); + return this.http + .get(`${this.apiPath}/restitution_relationships`, { headers: this.headers }) + .pipe(retry(3), catchError(this.handleError)); } getPoliceDetachments(): Observable { - return this.http.get(`${this.apiPath}/police_detachments`, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); + return this.http + .get(`${this.apiPath}/police_detachments`, { headers: this.headers }) + .pipe(retry(3), catchError(this.handleError)); } getCourts(): Observable { - return this.http.get(`${this.apiPath}/courts`, { headers: this.headers }).pipe( - retry(3), - catchError(this.handleError) - ); + return this.http + .get(`${this.apiPath}/courts`, { headers: this.headers }) + .pipe(retry(3), catchError(this.handleError)); } - get headers(): HttpHeaders { return new HttpHeaders({ 'Content-Type': 'application/json' }); } diff --git a/vsd-app/ClientApp/src/app/services/state.service.ts b/vsd-app/ClientApp/src/app/services/state.service.ts index e5e1d2a0..f7347027 100644 --- a/vsd-app/ClientApp/src/app/services/state.service.ts +++ b/vsd-app/ClientApp/src/app/services/state.service.ts @@ -2,7 +2,7 @@ import { Injectable } from '@angular/core'; @Injectable() export class StateService { - data: any; - cloning: boolean = false; - constructor() { } + data: any; + cloning: boolean = false; + constructor() {} } diff --git a/vsd-app/ClientApp/src/app/services/titile.service.ts b/vsd-app/ClientApp/src/app/services/titile.service.ts index 4938f674..c46ac636 100644 --- a/vsd-app/ClientApp/src/app/services/titile.service.ts +++ b/vsd-app/ClientApp/src/app/services/titile.service.ts @@ -1,9 +1,9 @@ -import { BehaviorSubject } from "rxjs"; +import { BehaviorSubject } from 'rxjs'; export class HeaderTitleService { - title = new BehaviorSubject('Crime Victim Assistance Program'); - - setTitle(title: string) { - this.title.next(title); - } - } \ No newline at end of file + title = new BehaviorSubject('Crime Victim Assistance Program'); + + setTitle(title: string) { + this.title.next(title); + } +} diff --git a/vsd-app/ClientApp/src/app/shared/address/address.component.spec.ts b/vsd-app/ClientApp/src/app/shared/address/address.component.spec.ts index 5b584812..be8eca80 100644 --- a/vsd-app/ClientApp/src/app/shared/address/address.component.spec.ts +++ b/vsd-app/ClientApp/src/app/shared/address/address.component.spec.ts @@ -8,9 +8,8 @@ describe('AddressComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - declarations: [ AddressComponent ] - }) - .compileComponents(); + declarations: [AddressComponent] + }).compileComponents(); })); beforeEach(() => { diff --git a/vsd-app/ClientApp/src/app/shared/address/address.component.ts b/vsd-app/ClientApp/src/app/shared/address/address.component.ts index 6780f33d..33594ef7 100644 --- a/vsd-app/ClientApp/src/app/shared/address/address.component.ts +++ b/vsd-app/ClientApp/src/app/shared/address/address.component.ts @@ -1,5 +1,5 @@ import { Component, OnInit, Input } from '@angular/core'; -import { FormGroup, Validators, FormControl } from "@angular/forms"; +import { FormGroup, Validators, FormControl } from '@angular/forms'; import { COUNTRIES_ADDRESS } from './country-list'; import { POSTAL_CODE, ZIP_CODE } from '../regex.constants'; import { CitiesSearchResponse, iCity, iCountry, iLookupData, iProvince } from '../../interfaces/lookup-data.interface'; @@ -42,9 +42,8 @@ export class AddressComponent implements OnInit { @Input() isDisabled: boolean = false; @Input() lookupData: iLookupData; - constructor(public lookupService: LookupService, - private http: HttpClient,) { - let canada = COUNTRIES_ADDRESS.filter(c => c.name.toLowerCase() == 'canada')[0]; + constructor(public lookupService: LookupService, private http: HttpClient) { + let canada = COUNTRIES_ADDRESS.filter((c) => c.name.toLowerCase() == 'canada')[0]; this.provinceType = canada.areaType; this.postalCodeType = canada.postalCodeName; this.postalCodeSample = canada.postalCodeSample; @@ -81,13 +80,15 @@ export class AddressComponent implements OnInit { if (data && data.CityCollection) { data.CityCollection.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); return data.CityCollection; - } - else return []; + } else return []; }), - tap(() => noop, err => { - // in case of http error - this.errorMessage = err && err.message || 'Something goes wrong'; - }) + tap( + () => noop, + (err) => { + // in case of http error + this.errorMessage = (err && err.message) || 'Something goes wrong'; + } + ) ); } return of([]); @@ -99,31 +100,35 @@ export class AddressComponent implements OnInit { let promise_array = []; if (!this.lookupData.countries || this.lookupData.countries.length == 0) { - promise_array.push(new Promise((resolve, reject) => { - this.lookupService.getCountries().subscribe((res) => { - this.lookupData.countries = res.value; - if (this.lookupData.countries) { - this.lookupData.countries.sort(function (a, b) { - return a.vsd_name.localeCompare(b.vsd_name); - }); - } - resolve(); - }); - })); + promise_array.push( + new Promise((resolve, reject) => { + this.lookupService.getCountries().subscribe((res) => { + this.lookupData.countries = res.value; + if (this.lookupData.countries) { + this.lookupData.countries.sort(function (a, b) { + return a.vsd_name.localeCompare(b.vsd_name); + }); + } + resolve(); + }); + }) + ); } if (!this.lookupData.provinces || this.lookupData.provinces.length == 0) { - promise_array.push(new Promise((resolve, reject) => { - this.lookupService.getProvinces().subscribe((res) => { - this.lookupData.provinces = res.value; - if (this.lookupData.provinces) { - this.lookupData.provinces.sort(function (a, b) { - return a.vsd_name.localeCompare(b.vsd_name); - }); - } - resolve(); - }); - })); + promise_array.push( + new Promise((resolve, reject) => { + this.lookupService.getProvinces().subscribe((res) => { + this.lookupData.provinces = res.value; + if (this.lookupData.provinces) { + this.lookupData.provinces.sort(function (a, b) { + return a.vsd_name.localeCompare(b.vsd_name); + }); + } + resolve(); + }); + }) + ); } Promise.all(promise_array).then((res) => { @@ -136,48 +141,58 @@ export class AddressComponent implements OnInit { this.showChildrenAsRequired = true; } - let pref_countries = this.lookupData.countries.filter(c => config.preferred_countries.findIndex(pc => pc.vsd_countryid == c.vsd_countryid) >= 0); - let remaining_countries = this.lookupData.countries.filter(c => config.preferred_countries.findIndex(pc => pc.vsd_countryid == c.vsd_countryid) < 0); + let pref_countries = this.lookupData.countries.filter( + (c) => config.preferred_countries.findIndex((pc) => pc.vsd_countryid == c.vsd_countryid) >= 0 + ); + let remaining_countries = this.lookupData.countries.filter( + (c) => config.preferred_countries.findIndex((pc) => pc.vsd_countryid == c.vsd_countryid) < 0 + ); pref_countries.sort(function (a, b) { - return config.preferred_countries.findIndex(c => c.vsd_countryid == a.vsd_countryid) - config.preferred_countries.findIndex(c => c.vsd_countryid == b.vsd_countryid); + return ( + config.preferred_countries.findIndex((c) => c.vsd_countryid == a.vsd_countryid) - + config.preferred_countries.findIndex((c) => c.vsd_countryid == b.vsd_countryid) + ); }); - if (!this.alreadyHasOtherOption(pref_countries) && !this.alreadyHasOtherOption(remaining_countries)) pref_countries.unshift(config.other_country); + if (!this.alreadyHasOtherOption(pref_countries) && !this.alreadyHasOtherOption(remaining_countries)) + pref_countries.unshift(config.other_country); remaining_countries.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); this.countryList = pref_countries.concat(remaining_countries); this.cityList = this.lookupData.cities; this.cityList.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); - let other_city_index = this.getOtherIndex(this.cityList) + let other_city_index = this.getOtherIndex(this.cityList); if (other_city_index < 0) { this.cityList.unshift(config.other_city); - } - else { + } else { let other_city = this.cityList.splice(other_city_index, 1)[0]; this.cityList.unshift(other_city); } - let canada = COUNTRIES_ADDRESS.filter(c => c.name.toLowerCase() == 'canada')[0]; + let canada = COUNTRIES_ADDRESS.filter((c) => c.name.toLowerCase() == 'canada')[0]; this.provinceType = canada.areaType; this.postalCodeType = canada.postalCodeName; this.postalCodeSample = canada.postalCodeSample; let countryVal = this.group['controls']['country'].value.toString(); - this.selectedCountry = this.lookupData.countries.filter(c => c.vsd_name.toLowerCase() == countryVal.toLowerCase())[0]; - if (countryVal === "Other") this.selectedCountry = { vsd_name: "Other", vsd_countryid: "123" }; + this.selectedCountry = this.lookupData.countries.filter( + (c) => c.vsd_name.toLowerCase() == countryVal.toLowerCase() + )[0]; + if (countryVal === 'Other') this.selectedCountry = { vsd_name: 'Other', vsd_countryid: '123' }; if (!this.selectedCountry) { - this.selectedCountry = this.lookupData.countries.filter(p => p.vsd_name.toLowerCase() === 'canada')[0]; + this.selectedCountry = this.lookupData.countries.filter((p) => p.vsd_name.toLowerCase() === 'canada')[0]; } if (this.selectedCountry) { - this.provinceList = this.lookupData.provinces.filter(p => p._vsd_countryid_value === this.selectedCountry.vsd_countryid); + this.provinceList = this.lookupData.provinces.filter( + (p) => p._vsd_countryid_value === this.selectedCountry.vsd_countryid + ); this.provinceList.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); - let other_province_index = this.getOtherIndex(this.provinceList) + let other_province_index = this.getOtherIndex(this.provinceList); if (other_province_index < 0) { this.provinceList.unshift(config.other_province); - } - else { + } else { let other_province = this.provinceList.splice(other_province_index, 1)[0]; this.provinceList.unshift(other_province); } @@ -188,19 +203,18 @@ export class AddressComponent implements OnInit { } let provinceVal = this.group['controls']['province'].value.toString(); - this.selectedProvince = this.lookupData.provinces.filter(c => c.vsd_name.toLowerCase() == provinceVal.toLowerCase())[0]; - if (this.selectedProvince.vsd_name != "British Columbia") - this.updateCityList(); - else - this.setCityValidators(); + this.selectedProvince = this.lookupData.provinces.filter( + (c) => c.vsd_name.toLowerCase() == provinceVal.toLowerCase() + )[0]; + if (this.selectedProvince.vsd_name != 'British Columbia') this.updateCityList(); + else this.setCityValidators(); this.setProvinceValidators(); } isSubFieldValid(field: string, disabled: boolean) { if (disabled === true) return true; let formField = this.group['controls'][field]; - if (formField == null) - return true; + if (formField == null) return true; return formField.valid || !formField.touched; } @@ -208,22 +222,23 @@ export class AddressComponent implements OnInit { onCountryChange(event) { let provinceControl = this.group['controls']['province'] as FormControl; provinceControl.patchValue(''); - this.selectedProvince = { vsd_name: "", _vsd_countryid_value: "", vsd_code: "", vsd_provinceid: "" }; + this.selectedProvince = { vsd_name: '', _vsd_countryid_value: '', vsd_code: '', vsd_provinceid: '' }; let cityControl = this.group['controls']['city'] as FormControl; cityControl.patchValue(''); let selection = event.target.value.toLowerCase(); - this.selectedCountry = this.lookupData.countries.filter(c => c.vsd_name.toLowerCase() == selection)[0]; + this.selectedCountry = this.lookupData.countries.filter((c) => c.vsd_name.toLowerCase() == selection)[0]; if (this.selectedCountry) { - this.provinceList = this.lookupData.provinces.filter(p => p._vsd_countryid_value === this.selectedCountry.vsd_countryid); + this.provinceList = this.lookupData.provinces.filter( + (p) => p._vsd_countryid_value === this.selectedCountry.vsd_countryid + ); if (this.provinceList) { this.provinceList.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); } - let other_province_index = this.getOtherIndex(this.provinceList) + let other_province_index = this.getOtherIndex(this.provinceList); if (other_province_index < 0) { this.provinceList.unshift(config.other_province); - } - else { + } else { let other_province = this.provinceList.splice(other_province_index, 1)[0]; this.provinceList.unshift(other_province); } @@ -236,10 +251,9 @@ export class AddressComponent implements OnInit { this.setProvinceAndPostalType(this.selectedCountry.vsd_name); this.updateCityList(); - } - else { + } else { this.provinceList = [config.other_province]; - this.setProvinceAndPostalType(""); + this.setProvinceAndPostalType(''); this.cityList = [config.other_city]; this.setCityValidators(); } @@ -249,35 +263,39 @@ export class AddressComponent implements OnInit { let cityControl = this.group['controls']['city'] as FormControl; cityControl.patchValue(''); let selection = event.target.value.toLowerCase(); - this.selectedProvince = this.lookupData.provinces.filter(c => c.vsd_name.toLowerCase() == selection)[0]; + this.selectedProvince = this.lookupData.provinces.filter((c) => c.vsd_name.toLowerCase() == selection)[0]; this.updateCityList(); } updateCityList() { - if (this.selectedProvince && this.selectedCountry && this.selectedCountry.vsd_countryid && this.selectedProvince.vsd_provinceid) { - this.lookupService.getCitiesByProvince(this.selectedCountry.vsd_countryid, this.selectedProvince.vsd_provinceid).subscribe((city_res) => { - // console.log(city_res); - if (city_res.value) { - this.cityList = city_res.value; - if (this.cityList) { - this.cityList.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); - } - let other_city_index = this.getOtherIndex(this.cityList) - if (other_city_index < 0) { - this.cityList.unshift(config.other_city); - } - else { - let other_city = this.cityList.splice(other_city_index, 1)[0]; - this.cityList.unshift(other_city); + if ( + this.selectedProvince && + this.selectedCountry && + this.selectedCountry.vsd_countryid && + this.selectedProvince.vsd_provinceid + ) { + this.lookupService + .getCitiesByProvince(this.selectedCountry.vsd_countryid, this.selectedProvince.vsd_provinceid) + .subscribe((city_res) => { + // console.log(city_res); + if (city_res.value) { + this.cityList = city_res.value; + if (this.cityList) { + this.cityList.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); + } + let other_city_index = this.getOtherIndex(this.cityList); + if (other_city_index < 0) { + this.cityList.unshift(config.other_city); + } else { + let other_city = this.cityList.splice(other_city_index, 1)[0]; + this.cityList.unshift(other_city); + } + } else { + this.cityList = [config.other_city]; } - } - else { - this.cityList = [config.other_city]; - } - this.setCityValidators(); - }); - } - else if (this.provinceList.length == 1 && this.selectedCountry && this.selectedCountry.vsd_countryid) { + this.setCityValidators(); + }); + } else if (this.provinceList.length == 1 && this.selectedCountry && this.selectedCountry.vsd_countryid) { this.lookupService.getCitiesByCountry(this.selectedCountry.vsd_countryid).subscribe((city_res) => { // console.log(city_res); if (city_res.value) { @@ -285,22 +303,19 @@ export class AddressComponent implements OnInit { if (this.cityList) { this.cityList.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); } - let other_city_index = this.getOtherIndex(this.cityList) + let other_city_index = this.getOtherIndex(this.cityList); if (other_city_index < 0) { this.cityList.unshift(config.other_city); - } - else { + } else { let other_city = this.cityList.splice(other_city_index, 1)[0]; this.cityList.unshift(other_city); } - } - else { + } else { this.cityList = [config.other_city]; } this.setCityValidators(); }); - } - else { + } else { this.cityList = [config.other_city]; this.setCityValidators(); } @@ -311,27 +326,24 @@ export class AddressComponent implements OnInit { if (country.toLowerCase() === 'canada') { if (this.showChildrenAsRequired) { postalControl.setValidators([Validators.required, Validators.pattern(this.postalRegex)]); - } - else { + } else { postalControl.setValidators([Validators.pattern(this.postalRegex)]); } - let canada = COUNTRIES_ADDRESS.filter(c => c.name.toLowerCase() == 'canada')[0]; + let canada = COUNTRIES_ADDRESS.filter((c) => c.name.toLowerCase() == 'canada')[0]; this.provinceType = canada.areaType; this.postalCodeType = canada.postalCodeName; this.postalCodeSample = canada.postalCodeSample; - } - else if (country.toLowerCase() === 'united states of america') { + } else if (country.toLowerCase() === 'united states of america') { postalControl.setValidators([Validators.pattern(this.zipRegex)]); - let usa = COUNTRIES_ADDRESS.filter(c => c.name.toLowerCase() == 'united states of america')[0]; + let usa = COUNTRIES_ADDRESS.filter((c) => c.name.toLowerCase() == 'united states of america')[0]; this.provinceType = usa.areaType; this.postalCodeType = usa.postalCodeName; this.postalCodeSample = usa.postalCodeSample; - } - else { + } else { postalControl.clearValidators(); - this.provinceType = "Province/State"; - this.postalCodeType = "Postal/ZIP Code"; - this.postalCodeSample = ""; + this.provinceType = 'Province/State'; + this.postalCodeType = 'Postal/ZIP Code'; + this.postalCodeSample = ''; } postalControl.updateValueAndValidity(); } @@ -342,8 +354,7 @@ export class AddressComponent implements OnInit { provinceControl.setErrors(null); provinceControl.disable(); this.isProvinceDisabled = true; - } - else { + } else { provinceControl.enable(); this.isProvinceDisabled = false; } @@ -357,18 +368,17 @@ export class AddressComponent implements OnInit { cityControl.setErrors(null); cityControl.disable(); this.isCityDisabled = true; - } - else { + } else { cityControl.enable(); this.isCityDisabled = false; } } alreadyHasOtherOption(list: any) { - return list.findIndex(o => o.vsd_name == "Other") >= 0; + return list.findIndex((o) => o.vsd_name == 'Other') >= 0; } getOtherIndex(list: any) { - return list.findIndex(o => o.vsd_name == "Other"); + return list.findIndex((o) => o.vsd_name == 'Other'); } -} \ No newline at end of file +} diff --git a/vsd-app/ClientApp/src/app/shared/address/address.helper.ts b/vsd-app/ClientApp/src/app/shared/address/address.helper.ts index f1dbb2d7..e888948f 100644 --- a/vsd-app/ClientApp/src/app/shared/address/address.helper.ts +++ b/vsd-app/ClientApp/src/app/shared/address/address.helper.ts @@ -1,124 +1,115 @@ -import { POSTAL_CODE, ZIP_CODE } from "../regex.constants"; -import { FormGroup, Validators } from "@angular/forms"; -import { Address } from "../../interfaces/address.interface"; +import { POSTAL_CODE, ZIP_CODE } from '../regex.constants'; +import { FormGroup, Validators } from '@angular/forms'; +import { Address } from '../../interfaces/address.interface'; export class AddressHelper { - postalRegex = POSTAL_CODE; - zipRegex = ZIP_CODE; - - public clearAddressValidatorsAndErrors(form: FormGroup, field: string) { - let options = { onlySelf: false, emitEvent: true }; - let addressControls = [ - form.get(field + '.country'), - form.get(field + '.province'), - form.get(field + '.city'), - form.get(field + '.line1'), - ]; - - let postalControl = form.get(field + '.postalCode'); - - for (let control of addressControls) { - control.clearValidators(); - control.setErrors(null, options); - // control.markAsTouched(); - control.updateValueAndValidity(options); - } - - if (form.get(field + '.country').value === "Canada") { - postalControl.setValidators([Validators.pattern(this.postalRegex)]); - } - else if (form.get(field + '.country').value === "United States of America") { - postalControl.setValidators([Validators.pattern(this.zipRegex)]); - } - else { - postalControl.clearValidators(); - } - - postalControl.setErrors(null, options); - // postalControl.markAsTouched(); - postalControl.updateValueAndValidity(options); + postalRegex = POSTAL_CODE; + zipRegex = ZIP_CODE; + + public clearAddressValidatorsAndErrors(form: FormGroup, field: string) { + let options = { onlySelf: false, emitEvent: true }; + let addressControls = [ + form.get(field + '.country'), + form.get(field + '.province'), + form.get(field + '.city'), + form.get(field + '.line1') + ]; + + let postalControl = form.get(field + '.postalCode'); + + for (let control of addressControls) { + control.clearValidators(); + control.setErrors(null, options); + // control.markAsTouched(); + control.updateValueAndValidity(options); } - public markAsTouched(form: FormGroup, field: string) { - let addressControls = [ - form.get(field + '.country'), - form.get(field + '.province'), - form.get(field + '.city'), - form.get(field + '.line1'), - ]; + if (form.get(field + '.country').value === 'Canada') { + postalControl.setValidators([Validators.pattern(this.postalRegex)]); + } else if (form.get(field + '.country').value === 'United States of America') { + postalControl.setValidators([Validators.pattern(this.zipRegex)]); + } else { + postalControl.clearValidators(); + } - let postalControl = form.get(field + '.postalCode'); + postalControl.setErrors(null, options); + // postalControl.markAsTouched(); + postalControl.updateValueAndValidity(options); + } - for (let control of addressControls) { - control.markAsTouched(); - } - postalControl.markAsTouched(); - } + public markAsTouched(form: FormGroup, field: string) { + let addressControls = [ + form.get(field + '.country'), + form.get(field + '.province'), + form.get(field + '.city'), + form.get(field + '.line1') + ]; - public setAddressAsRequired(form: FormGroup, field: string) { - let options = { onlySelf: false, emitEvent: true }; - let addressControls = [ - form.get(field + '.country'), - form.get(field + '.province'), - form.get(field + '.city'), - form.get(field + '.line1'), - ]; - - let postalControl = form.get(field + '.postalCode'); - - for (let control of addressControls) { - control.setValidators([Validators.required]); - // control.markAsTouched(); - control.updateValueAndValidity(options); - } - if (form.get(field + '.country').value === "Canada") { - postalControl.setValidators([Validators.required, Validators.pattern(this.postalRegex)]); - } - else if (form.get(field + '.country').value === "United States of America") { - postalControl.setValidators([Validators.required, Validators.pattern(this.zipRegex)]); - } - else { - postalControl.setValidators([Validators.required]); - } - // postalControl.markAsTouched(); - postalControl.updateValueAndValidity(options); - } + let postalControl = form.get(field + '.postalCode'); - public hasAddressInfo(address: Address) { - if (address.line1 || address.line2 || address.city || address.postalCode) { - return true; - } - return false; + for (let control of addressControls) { + control.markAsTouched(); } - - public clearAddress(form: FormGroup, field: string) { - let addressControls = [ - form.get(field + '.city'), - form.get(field + '.line1'), - form.get(field + '.line2'), - form.get(field + '.postalCode'), - ]; - form.get(field + '.country').patchValue('Canada'); - form.get(field + '.province').patchValue('British Columbia'); - - for (let control of addressControls) { - control.patchValue(''); - } + postalControl.markAsTouched(); + } + + public setAddressAsRequired(form: FormGroup, field: string) { + let options = { onlySelf: false, emitEvent: true }; + let addressControls = [ + form.get(field + '.country'), + form.get(field + '.province'), + form.get(field + '.city'), + form.get(field + '.line1') + ]; + + let postalControl = form.get(field + '.postalCode'); + + for (let control of addressControls) { + control.setValidators([Validators.required]); + // control.markAsTouched(); + control.updateValueAndValidity(options); + } + if (form.get(field + '.country').value === 'Canada') { + postalControl.setValidators([Validators.required, Validators.pattern(this.postalRegex)]); + } else if (form.get(field + '.country').value === 'United States of America') { + postalControl.setValidators([Validators.required, Validators.pattern(this.zipRegex)]); + } else { + postalControl.setValidators([Validators.required]); } + // postalControl.markAsTouched(); + postalControl.updateValueAndValidity(options); + } - public displayAddress(address: Address) { - let display = address.line1 + '
'; - if (address.line2 != '') - display += address.line2 + '
'; - if (address.city != '') - display += address.city + '
'; - if (address.province != '') - display += address.province + '
'; - if (address.country != '') - display += address.country + '
'; - if (address.postalCode != '') - display += address.postalCode; - - return display; + public hasAddressInfo(address: Address) { + if (address.line1 || address.line2 || address.city || address.postalCode) { + return true; + } + return false; + } + + public clearAddress(form: FormGroup, field: string) { + let addressControls = [ + form.get(field + '.city'), + form.get(field + '.line1'), + form.get(field + '.line2'), + form.get(field + '.postalCode') + ]; + form.get(field + '.country').patchValue('Canada'); + form.get(field + '.province').patchValue('British Columbia'); + + for (let control of addressControls) { + control.patchValue(''); } -} \ No newline at end of file + } + + public displayAddress(address: Address) { + let display = address.line1 + '
'; + if (address.line2 != '') display += address.line2 + '
'; + if (address.city != '') display += address.city + '
'; + if (address.province != '') display += address.province + '
'; + if (address.country != '') display += address.country + '
'; + if (address.postalCode != '') display += address.postalCode; + + return display; + } +} diff --git a/vsd-app/ClientApp/src/app/shared/address/country-list.ts b/vsd-app/ClientApp/src/app/shared/address/country-list.ts index 0b8fe400..08791737 100644 --- a/vsd-app/ClientApp/src/app/shared/address/country-list.ts +++ b/vsd-app/ClientApp/src/app/shared/address/country-list.ts @@ -25,7 +25,7 @@ export const COUNTRIES_ADDRESS: iCountry[] = [ 'Prince Edward Island', 'Quebec', 'Saskatchewan', - 'Yukon', + 'Yukon' ] }, { @@ -34,7 +34,65 @@ export const COUNTRIES_ADDRESS: iCountry[] = [ postalCodeSample: '10001', areaType: 'State', areas: [ - 'Alabama', 'Alaska', 'American Samoa', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'District of Columbia', 'Federated States of Micronesia', 'Florida', 'Georgia', 'Guam', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Marshall Islands', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Northern Mariana Islands', 'Ohio', 'Oklahoma', 'Oregon', 'Palau', 'Pennsylvania', 'Puerto Rico', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virgin Island', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming' + 'Alabama', + 'Alaska', + 'American Samoa', + 'Arizona', + 'Arkansas', + 'California', + 'Colorado', + 'Connecticut', + 'Delaware', + 'District of Columbia', + 'Federated States of Micronesia', + 'Florida', + 'Georgia', + 'Guam', + 'Hawaii', + 'Idaho', + 'Illinois', + 'Indiana', + 'Iowa', + 'Kansas', + 'Kentucky', + 'Louisiana', + 'Maine', + 'Marshall Islands', + 'Maryland', + 'Massachusetts', + 'Michigan', + 'Minnesota', + 'Mississippi', + 'Missouri', + 'Montana', + 'Nebraska', + 'Nevada', + 'New Hampshire', + 'New Jersey', + 'New Mexico', + 'New York', + 'North Carolina', + 'North Dakota', + 'Northern Mariana Islands', + 'Ohio', + 'Oklahoma', + 'Oregon', + 'Palau', + 'Pennsylvania', + 'Puerto Rico', + 'Rhode Island', + 'South Carolina', + 'South Dakota', + 'Tennessee', + 'Texas', + 'Utah', + 'Vermont', + 'Virgin Island', + 'Virginia', + 'Washington', + 'West Virginia', + 'Wisconsin', + 'Wyoming' ] }, { @@ -48,7 +106,7 @@ export const COUNTRIES_ADDRESS: iCountry[] = [ // the one above is basically useless for addressing. I left it because I don't want broken forms. You must iterate and check the name to get a value. So wasteful on resources. export const COUNTRIES_ADDRESS_2 = { - 'Canada': { + Canada: { name: 'Canada', postalCodeName: 'Postal Code', postalCodeSample: 'V9A 0A9', @@ -66,7 +124,7 @@ export const COUNTRIES_ADDRESS_2 = { 'Prince Edward Island', 'Quebec', 'Saskatchewan', - 'Yukon', + 'Yukon' ] } as iCountry, 'United States of America': { @@ -75,7 +133,65 @@ export const COUNTRIES_ADDRESS_2 = { postalCodeSample: '10001', areaType: 'State', areas: [ - 'Alabama', 'Alaska', 'American Samoa', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'District of Columbia', 'Federated States of Micronesia', 'Florida', 'Georgia', 'Guam', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Marshall Islands', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Northern Mariana Islands', 'Ohio', 'Oklahoma', 'Oregon', 'Palau', 'Pennsylvania', 'Puerto Rico', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virgin Island', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming' + 'Alabama', + 'Alaska', + 'American Samoa', + 'Arizona', + 'Arkansas', + 'California', + 'Colorado', + 'Connecticut', + 'Delaware', + 'District of Columbia', + 'Federated States of Micronesia', + 'Florida', + 'Georgia', + 'Guam', + 'Hawaii', + 'Idaho', + 'Illinois', + 'Indiana', + 'Iowa', + 'Kansas', + 'Kentucky', + 'Louisiana', + 'Maine', + 'Marshall Islands', + 'Maryland', + 'Massachusetts', + 'Michigan', + 'Minnesota', + 'Mississippi', + 'Missouri', + 'Montana', + 'Nebraska', + 'Nevada', + 'New Hampshire', + 'New Jersey', + 'New Mexico', + 'New York', + 'North Carolina', + 'North Dakota', + 'Northern Mariana Islands', + 'Ohio', + 'Oklahoma', + 'Oregon', + 'Palau', + 'Pennsylvania', + 'Puerto Rico', + 'Rhode Island', + 'South Carolina', + 'South Dakota', + 'Tennessee', + 'Texas', + 'Utah', + 'Vermont', + 'Virgin Island', + 'Virginia', + 'Washington', + 'West Virginia', + 'Wisconsin', + 'Wyoming' ] } as iCountry, 'Other Country': { @@ -85,4 +201,4 @@ export const COUNTRIES_ADDRESS_2 = { areaType: 'Province/State', areas: [] } as iCountry -} +}; diff --git a/vsd-app/ClientApp/src/app/shared/application-review/application-review.component.scss b/vsd-app/ClientApp/src/app/shared/application-review/application-review.component.scss index ab508056..3ec63c0c 100644 --- a/vsd-app/ClientApp/src/app/shared/application-review/application-review.component.scss +++ b/vsd-app/ClientApp/src/app/shared/application-review/application-review.component.scss @@ -1,48 +1,48 @@ h3 span { - font-size: 14px; - font-weight: 400; + font-size: 14px; + font-weight: 400; } h1, h2, h3 { - font-weight: 600; + font-weight: 600; } h2, h3 { - margin-top: 30px; - margin-bottom: 20px; + margin-top: 30px; + margin-bottom: 20px; } .review-table { - border-collapse: separate; - border-spacing: 3px; - - tr { - background-color: #f1f4fa; - - th, - td { - //background-color: #e1e8f2; - border: 0 !important; - } - - th { - font-weight: normal; - width: 30%; - } - - td { - font-weight: bold; - width: 70%; - max-width: 440px; - overflow: hidden; - text-overflow: ellipsis; - } + border-collapse: separate; + border-spacing: 3px; + + tr { + background-color: #f1f4fa; + + th, + td { + //background-color: #e1e8f2; + border: 0 !important; } - &.table-striped > tbody > tr:nth-of-type(odd) { - background-color: #e1e8f2; + th { + font-weight: normal; + width: 30%; } + + td { + font-weight: bold; + width: 70%; + max-width: 440px; + overflow: hidden; + text-overflow: ellipsis; + } + } + + &.table-striped > tbody > tr:nth-of-type(odd) { + background-color: #e1e8f2; + } } diff --git a/vsd-app/ClientApp/src/app/shared/application-review/application-review.component.ts b/vsd-app/ClientApp/src/app/shared/application-review/application-review.component.ts index f820db20..88f5b839 100644 --- a/vsd-app/ClientApp/src/app/shared/application-review/application-review.component.ts +++ b/vsd-app/ClientApp/src/app/shared/application-review/application-review.component.ts @@ -1,116 +1,114 @@ -import { FormBase } from "../form-base"; -import { OnInit, Component, Input } from "@angular/core"; -import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS, MatDialog, MatStepper } from "@angular/material"; -import { FormGroup, ControlContainer, FormArray } from "@angular/forms"; -import { MomentDateAdapter } from "@angular/material-moment-adapter"; -import { MY_FORMATS, ApplicationType, EnumHelper, OnBehalfOf, CRMBoolean, CRMMultiBoolean } from "../enums-list"; -import { AddressHelper } from "../address/address.helper"; +import { FormBase } from '../form-base'; +import { OnInit, Component, Input } from '@angular/core'; +import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS, MatDialog, MatStepper } from '@angular/material'; +import { FormGroup, ControlContainer, FormArray } from '@angular/forms'; +import { MomentDateAdapter } from '@angular/material-moment-adapter'; +import { MY_FORMATS, ApplicationType, EnumHelper, OnBehalfOf, CRMBoolean, CRMMultiBoolean } from '../enums-list'; +import { AddressHelper } from '../address/address.helper'; @Component({ - selector: 'app-application-review', - templateUrl: './application-review.component.html', - styleUrls: ['./application-review.component.scss'], - providers: [ - // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your - // application's root module. We provide it at the component level here, due to limitations of - // our example generation script. - { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, - { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }, - ], + selector: 'app-application-review', + templateUrl: './application-review.component.html', + styleUrls: ['./application-review.component.scss'], + providers: [ + // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your + // application's root module. We provide it at the component level here, due to limitations of + // our example generation script. + { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, + { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS } + ] }) export class ApplicationReviewComponent extends FormBase implements OnInit { - @Input() formType: number; - @Input() parentStepper: MatStepper; - public form: FormGroup; - ApplicationType = ApplicationType; - CRMBoolean = CRMBoolean; - CRMMultiBoolean = CRMMultiBoolean; - OnBehalfOf = OnBehalfOf; - enumHelper = new EnumHelper(); + @Input() formType: number; + @Input() parentStepper: MatStepper; + public form: FormGroup; + ApplicationType = ApplicationType; + CRMBoolean = CRMBoolean; + CRMMultiBoolean = CRMMultiBoolean; + OnBehalfOf = OnBehalfOf; + enumHelper = new EnumHelper(); - courtFiles: FormArray; - crimeLocations: FormArray; - policeReports: FormArray; - otherMedicalTreatments: FormArray; - employers: FormArray; + courtFiles: FormArray; + crimeLocations: FormArray; + policeReports: FormArray; + otherMedicalTreatments: FormArray; + employers: FormArray; - addressHelper = new AddressHelper(); + addressHelper = new AddressHelper(); - pages: any; + pages: any; + constructor(private controlContainer: ControlContainer) { + super(); + } - - constructor( - private controlContainer: ControlContainer, - ) { - super(); + ngOnInit() { + this.form = this.controlContainer.control; + setTimeout(() => { + this.form.markAsTouched(); + }, 0); + this.crimeLocations = this.form.get('crimeInformation.crimeLocations') as FormArray; + this.courtFiles = this.form.get('crimeInformation.courtFiles') as FormArray; + this.policeReports = this.form.get('crimeInformation.policeReports') as FormArray; + this.otherMedicalTreatments = this.form.get('medicalInformation.otherTreatments') as FormArray; + if (this.formType === ApplicationType.Victim_Application) { + this.employers = this.form.get('employmentIncomeInformation.employers') as FormArray; + this.pages = VictimApplicationPages; } - - ngOnInit() { - this.form = this.controlContainer.control; - setTimeout(() => { this.form.markAsTouched(); }, 0); - this.crimeLocations = this.form.get('crimeInformation.crimeLocations') as FormArray; - this.courtFiles = this.form.get('crimeInformation.courtFiles') as FormArray; - this.policeReports = this.form.get('crimeInformation.policeReports') as FormArray; - this.otherMedicalTreatments = this.form.get('medicalInformation.otherTreatments') as FormArray; - if (this.formType === ApplicationType.Victim_Application) { - this.employers = this.form.get('employmentIncomeInformation.employers') as FormArray; - this.pages = VictimApplicationPages; - } - if (this.formType === ApplicationType.IFM_Application) { - this.employers = this.form.get('expenseInformation.employers') as FormArray; - this.pages = IFMApplicationPages; - } - if (this.formType === ApplicationType.Witness_Application) { - this.pages = WitnessApplicationPages; - } - // console.log("review component"); - // console.log(this.form); - - // console.log(this.pages); + if (this.formType === ApplicationType.IFM_Application) { + this.employers = this.form.get('expenseInformation.employers') as FormArray; + this.pages = IFMApplicationPages; } - - gotoPageIndex(selectPage: number): void { - window.scroll(0, 0); - this.parentStepper.selectedIndex = selectPage; + if (this.formType === ApplicationType.Witness_Application) { + this.pages = WitnessApplicationPages; } + // console.log("review component"); + // console.log(this.form); + + // console.log(this.pages); + } + + gotoPageIndex(selectPage: number): void { + window.scroll(0, 0); + this.parentStepper.selectedIndex = selectPage; + } } enum VictimApplicationPages { - Overview, - Personal, - Crime, - Medical, - Expense, - Employment, - OnBehalfOf, - Declaration, - Authorization, - Review + Overview, + Personal, + Crime, + Medical, + Expense, + Employment, + OnBehalfOf, + Declaration, + Authorization, + Review } enum IFMApplicationPages { - Overview, - Personal, - Victim, - Crime, - Medical, - Expense, - OnBehalfOf, - Declaration, - Authorization, - Review + Overview, + Personal, + Victim, + Crime, + Medical, + Expense, + OnBehalfOf, + Declaration, + Authorization, + Review } enum WitnessApplicationPages { - Overview, - Personal, - Victim, - Crime, - Medical, - Expense, - OnBehalfOf, - Declaration, - Authorization, - Review -} \ No newline at end of file + Overview, + Personal, + Victim, + Crime, + Medical, + Expense, + OnBehalfOf, + Declaration, + Authorization, + Review +} diff --git a/vsd-app/ClientApp/src/app/shared/authorization-information/authorization-information.component.ts b/vsd-app/ClientApp/src/app/shared/authorization-information/authorization-information.component.ts index c8702868..cd98c618 100644 --- a/vsd-app/ClientApp/src/app/shared/authorization-information/authorization-information.component.ts +++ b/vsd-app/ClientApp/src/app/shared/authorization-information/authorization-information.component.ts @@ -1,203 +1,203 @@ -import { FormBase } from "../form-base"; -import { Input, Component, OnInit, OnDestroy } from "@angular/core"; -import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS, MatDialog, MatDialogConfig } from "@angular/material"; -import { MomentDateAdapter } from "@angular/material-moment-adapter"; -import { MY_FORMATS, ApplicationType, EnumHelper, CRMBoolean } from "../enums-list"; -import { FormGroup, ControlContainer, FormBuilder, FormArray, Validators, AbstractControl } from "@angular/forms"; -import { SignPadDialog } from "../../sign-dialog/sign-dialog.component"; -import { POSTAL_CODE } from "../regex.constants"; -import { AuthInfoHelper } from "./authorization-information.helper"; -import { iLookupData } from "../../interfaces/lookup-data.interface"; -import { LookupService } from "../../services/lookup.service"; -import { Subscription } from "rxjs"; - +import { FormBase } from '../form-base'; +import { Input, Component, OnInit, OnDestroy } from '@angular/core'; +import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS, MatDialog, MatDialogConfig } from '@angular/material'; +import { MomentDateAdapter } from '@angular/material-moment-adapter'; +import { MY_FORMATS, ApplicationType, EnumHelper, CRMBoolean } from '../enums-list'; +import { FormGroup, ControlContainer, FormBuilder, FormArray, Validators, AbstractControl } from '@angular/forms'; +import { SignPadDialog } from '../../sign-dialog/sign-dialog.component'; +import { POSTAL_CODE } from '../regex.constants'; +import { AuthInfoHelper } from './authorization-information.helper'; +import { iLookupData } from '../../interfaces/lookup-data.interface'; +import { LookupService } from '../../services/lookup.service'; +import { Subscription } from 'rxjs'; @Component({ - selector: 'app-authorization-information', - templateUrl: './authorization-information.component.html', - styleUrls: ['./authorization-information.component.scss'], - providers: [ - // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your - // application's root module. We provide it at the component level here, due to limitations of - // our example generation script. - { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, - { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }, - ], + selector: 'app-authorization-information', + templateUrl: './authorization-information.component.html', + styleUrls: ['./authorization-information.component.scss'], + providers: [ + // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your + // application's root module. We provide it at the component level here, due to limitations of + // our example generation script. + { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, + { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS } + ] }) export class AuthorizationInformationComponent extends FormBase implements OnInit, OnDestroy { - @Input() formType: number; - @Input() lookupData: iLookupData; - public form: FormGroup; - ApplicationType = ApplicationType; - enumHelper = new EnumHelper(); - - authorizedPersons: FormArray; - showAddAuthorizationInformation: boolean = true; - showRemoveAuthorization: boolean = true; - postalRegex = POSTAL_CODE; - authInfoHelper = new AuthInfoHelper(); - - relationshipList: string[] = []; - - CRMBoolean = CRMBoolean; - - staffSharingSubscription: Subscription; - - constructor( - private controlContainer: ControlContainer, - private matDialog: MatDialog, - private fb: FormBuilder, - public lookupService: LookupService, - ) { - super(); - } - - ngOnInit() { - this.form = this.controlContainer.control; - setTimeout(() => { this.form.markAsTouched(); }, 0); - // console.log("auth info component"); - // console.log(this.form); - - this.staffSharingSubscription = this.form.get('allowCvapStaffSharing').valueChanges.subscribe(value => { - let options = { onlySelf: true, emitEvent: false }; - let authorizedPersonAuthorizesDiscussion = this.form.get('authorizedPersonAuthorizesDiscussion'); - let authorizedPersonSignature = this.form.get('authorizedPersonSignature'); - - authorizedPersonAuthorizesDiscussion.clearValidators(); - authorizedPersonAuthorizesDiscussion.setErrors(null, options); - authorizedPersonSignature.clearValidators(); - authorizedPersonSignature.setErrors(null), options; - - let useValidation = value === CRMBoolean.True; - if (useValidation) { - authorizedPersonAuthorizesDiscussion.setValidators([Validators.required]); - authorizedPersonSignature.setValidators([Validators.required]); - this.authorizedPersons = this.form.get('authorizedPerson') as FormArray; - if (this.authorizedPersons.length === 0) { - this.addAuthorizationInformation(true); - } - } - else { - this.clearAuthorizationInformation(); - } - - authorizedPersonAuthorizesDiscussion.updateValueAndValidity(options); - authorizedPersonSignature.updateValueAndValidity(options); - }); - - if (this.lookupData.relationships && this.lookupData.relationships.length > 0) { - this.relationshipList = this.lookupData.relationships.map(r => r.vsd_name); - } - else { - this.lookupService.getOptionalAuthorizationRelationships().subscribe((res) => { - this.lookupData.relationships = res.value; - if (this.lookupData.relationships) { - this.lookupData.relationships.sort(function (a, b) { - return a.vsd_name.localeCompare(b.vsd_name); - }); - } - this.relationshipList = this.lookupData.relationships.map(r => r.vsd_name); - }); - } - } - - ngOnDestroy() { - if (this.staffSharingSubscription) this.staffSharingSubscription.unsubscribe(); - } - - addAuthorizationInformation(makeAuthorizedSignatureRequired: boolean = false): void { - let options = { onlySelf: true, emitEvent: false }; + @Input() formType: number; + @Input() lookupData: iLookupData; + public form: FormGroup; + ApplicationType = ApplicationType; + enumHelper = new EnumHelper(); + + authorizedPersons: FormArray; + showAddAuthorizationInformation: boolean = true; + showRemoveAuthorization: boolean = true; + postalRegex = POSTAL_CODE; + authInfoHelper = new AuthInfoHelper(); + + relationshipList: string[] = []; + + CRMBoolean = CRMBoolean; + + staffSharingSubscription: Subscription; + + constructor( + private controlContainer: ControlContainer, + private matDialog: MatDialog, + private fb: FormBuilder, + public lookupService: LookupService + ) { + super(); + } + + ngOnInit() { + this.form = this.controlContainer.control; + setTimeout(() => { + this.form.markAsTouched(); + }, 0); + // console.log("auth info component"); + // console.log(this.form); + + this.staffSharingSubscription = this.form.get('allowCvapStaffSharing').valueChanges.subscribe((value) => { + let options = { onlySelf: true, emitEvent: false }; + let authorizedPersonAuthorizesDiscussion = this.form.get('authorizedPersonAuthorizesDiscussion'); + let authorizedPersonSignature = this.form.get('authorizedPersonSignature'); + + authorizedPersonAuthorizesDiscussion.clearValidators(); + authorizedPersonAuthorizesDiscussion.setErrors(null, options); + authorizedPersonSignature.clearValidators(); + authorizedPersonSignature.setErrors(null), options; + + let useValidation = value === CRMBoolean.True; + if (useValidation) { + authorizedPersonAuthorizesDiscussion.setValidators([Validators.required]); + authorizedPersonSignature.setValidators([Validators.required]); this.authorizedPersons = this.form.get('authorizedPerson') as FormArray; - let authPerson: FormGroup = this.authInfoHelper.createAuthorizedPerson(this.fb); - - this.authorizedPersons.push(authPerson); - this.showAddAuthorizationInformation = this.authorizedPersons.length < 3; - this.showRemoveAuthorization = this.authorizedPersons.length > 1; - - if (makeAuthorizedSignatureRequired) { - let authorizedPersonSignature = this.form.get('authorizedPersonSignature'); - authorizedPersonSignature.setErrors(null, options); - authorizedPersonSignature.setValidators([Validators.required]); - authorizedPersonSignature.updateValueAndValidity(options); + if (this.authorizedPersons.length === 0) { + this.addAuthorizationInformation(true); } - } - clearAuthorizationInformation(): void { - this.authorizedPersons = this.form.get('authorizedPerson') as FormArray; - while (this.authorizedPersons.length > 0) { - this.authorizedPersons.removeAt(this.authorizedPersons.length - 1); + } else { + this.clearAuthorizationInformation(); + } + + authorizedPersonAuthorizesDiscussion.updateValueAndValidity(options); + authorizedPersonSignature.updateValueAndValidity(options); + }); + + if (this.lookupData.relationships && this.lookupData.relationships.length > 0) { + this.relationshipList = this.lookupData.relationships.map((r) => r.vsd_name); + } else { + this.lookupService.getOptionalAuthorizationRelationships().subscribe((res) => { + this.lookupData.relationships = res.value; + if (this.lookupData.relationships) { + this.lookupData.relationships.sort(function (a, b) { + return a.vsd_name.localeCompare(b.vsd_name); + }); } - - let authorizedPersonSignature = this.form.get('authorizedPersonSignature'); - authorizedPersonSignature.setErrors(null); - authorizedPersonSignature.clearValidators(); - authorizedPersonSignature.updateValueAndValidity(); + this.relationshipList = this.lookupData.relationships.map((r) => r.vsd_name); + }); } - removeAuthorizationInformation(index: number): void { - this.authorizedPersons = this.form.get('authorizedPerson') as FormArray; - this.authorizedPersons.removeAt(index); - this.showAddAuthorizationInformation = this.authorizedPersons.length < 3; - this.showRemoveAuthorization = this.authorizedPersons.length > 1; + } + + ngOnDestroy() { + if (this.staffSharingSubscription) this.staffSharingSubscription.unsubscribe(); + } + + addAuthorizationInformation(makeAuthorizedSignatureRequired: boolean = false): void { + let options = { onlySelf: true, emitEvent: false }; + this.authorizedPersons = this.form.get('authorizedPerson') as FormArray; + let authPerson: FormGroup = this.authInfoHelper.createAuthorizedPerson(this.fb); + + this.authorizedPersons.push(authPerson); + this.showAddAuthorizationInformation = this.authorizedPersons.length < 3; + this.showRemoveAuthorization = this.authorizedPersons.length > 1; + + if (makeAuthorizedSignatureRequired) { + let authorizedPersonSignature = this.form.get('authorizedPersonSignature'); + authorizedPersonSignature.setErrors(null, options); + authorizedPersonSignature.setValidators([Validators.required]); + authorizedPersonSignature.updateValueAndValidity(options); } - - showSignPad(control): void { - const dialogConfig = new MatDialogConfig(); - dialogConfig.disableClose = true; - dialogConfig.autoFocus = true; - - const dialogRef = this.matDialog.open(SignPadDialog, dialogConfig); - dialogRef.afterClosed().subscribe( - data => { - var patchObject = {}; - patchObject[control] = data; - this.form.patchValue( - patchObject - ); - }, - err => console.log(err) - ); + } + clearAuthorizationInformation(): void { + this.authorizedPersons = this.form.get('authorizedPerson') as FormArray; + while (this.authorizedPersons.length > 0) { + this.authorizedPersons.removeAt(this.authorizedPersons.length - 1); } - setAuthPersonPhoneValidators(authPerson: AbstractControl) { - let phoneMinLength = 10; - let phoneMaxLength = 15; - if (authPerson.get('authorizedPersonAgencyAddress.country').value === 'Canada' || authPerson.get('authorizedPersonAgencyAddress.country').value === 'United States of America') { - phoneMinLength = 10; - } - else { - phoneMinLength = 8; - } - - let phoneControl = authPerson.get('authorizedPersonPhoneNumber'); - this.setControlValidators(phoneControl, [Validators.minLength(phoneMinLength), Validators.maxLength(phoneMaxLength)]); - phoneControl.patchValue(phoneControl.value); + let authorizedPersonSignature = this.form.get('authorizedPersonSignature'); + authorizedPersonSignature.setErrors(null); + authorizedPersonSignature.clearValidators(); + authorizedPersonSignature.updateValueAndValidity(); + } + removeAuthorizationInformation(index: number): void { + this.authorizedPersons = this.form.get('authorizedPerson') as FormArray; + this.authorizedPersons.removeAt(index); + this.showAddAuthorizationInformation = this.authorizedPersons.length < 3; + this.showRemoveAuthorization = this.authorizedPersons.length > 1; + } + + showSignPad(control): void { + const dialogConfig = new MatDialogConfig(); + dialogConfig.disableClose = true; + dialogConfig.autoFocus = true; + + const dialogRef = this.matDialog.open(SignPadDialog, dialogConfig); + dialogRef.afterClosed().subscribe( + (data) => { + var patchObject = {}; + patchObject[control] = data; + this.form.patchValue(patchObject); + }, + (err) => console.log(err) + ); + } + + setAuthPersonPhoneValidators(authPerson: AbstractControl) { + let phoneMinLength = 10; + let phoneMaxLength = 15; + if ( + authPerson.get('authorizedPersonAgencyAddress.country').value === 'Canada' || + authPerson.get('authorizedPersonAgencyAddress.country').value === 'United States of America' + ) { + phoneMinLength = 10; + } else { + phoneMinLength = 8; } - setAuthPersonAgencyAndNameValidators(authPerson: AbstractControl) { - let agencyControl = authPerson.get('authorizedPersonAgencyName'); - let authorizedPersonFirstNameControl = authPerson.get('authorizedPersonFirstName'); - let authorizedPersonLastNameControl = authPerson.get('authorizedPersonLastName'); - let authorizedPersonRelationshipControl = authPerson.get('authorizedPersonRelationship'); - if (authPerson.get('providerType').value === 'Person') { - this.setControlValidators(authorizedPersonFirstNameControl, [Validators.required]); - this.setControlValidators(authorizedPersonLastNameControl, [Validators.required]); - this.setControlValidators(authorizedPersonRelationshipControl, [Validators.required]); - - agencyControl.patchValue(''); - this.clearControlValidators(agencyControl); - } - else if (authPerson.get('providerType').value === 'Agency') { - this.setControlValidators(agencyControl, [Validators.required]); - - this.clearControlValidators(authorizedPersonFirstNameControl); - this.clearControlValidators(authorizedPersonLastNameControl); - this.clearControlValidators(authorizedPersonRelationshipControl); - } - else { - agencyControl.patchValue(''); - this.clearControlValidators(agencyControl); - this.clearControlValidators(authorizedPersonFirstNameControl); - this.clearControlValidators(authorizedPersonLastNameControl); - this.clearControlValidators(authorizedPersonRelationshipControl); - } + let phoneControl = authPerson.get('authorizedPersonPhoneNumber'); + this.setControlValidators(phoneControl, [ + Validators.minLength(phoneMinLength), + Validators.maxLength(phoneMaxLength) + ]); + phoneControl.patchValue(phoneControl.value); + } + + setAuthPersonAgencyAndNameValidators(authPerson: AbstractControl) { + let agencyControl = authPerson.get('authorizedPersonAgencyName'); + let authorizedPersonFirstNameControl = authPerson.get('authorizedPersonFirstName'); + let authorizedPersonLastNameControl = authPerson.get('authorizedPersonLastName'); + let authorizedPersonRelationshipControl = authPerson.get('authorizedPersonRelationship'); + if (authPerson.get('providerType').value === 'Person') { + this.setControlValidators(authorizedPersonFirstNameControl, [Validators.required]); + this.setControlValidators(authorizedPersonLastNameControl, [Validators.required]); + this.setControlValidators(authorizedPersonRelationshipControl, [Validators.required]); + + agencyControl.patchValue(''); + this.clearControlValidators(agencyControl); + } else if (authPerson.get('providerType').value === 'Agency') { + this.setControlValidators(agencyControl, [Validators.required]); + + this.clearControlValidators(authorizedPersonFirstNameControl); + this.clearControlValidators(authorizedPersonLastNameControl); + this.clearControlValidators(authorizedPersonRelationshipControl); + } else { + agencyControl.patchValue(''); + this.clearControlValidators(agencyControl); + this.clearControlValidators(authorizedPersonFirstNameControl); + this.clearControlValidators(authorizedPersonLastNameControl); + this.clearControlValidators(authorizedPersonRelationshipControl); } + } } diff --git a/vsd-app/ClientApp/src/app/shared/authorization-information/authorization-information.helper.ts b/vsd-app/ClientApp/src/app/shared/authorization-information/authorization-information.helper.ts index d7dfb77e..37566bb9 100644 --- a/vsd-app/ClientApp/src/app/shared/authorization-information/authorization-information.helper.ts +++ b/vsd-app/ClientApp/src/app/shared/authorization-information/authorization-information.helper.ts @@ -1,44 +1,43 @@ -import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms"; -import { ApplicationType } from "../enums-list"; -import { POSTAL_CODE } from "../regex.constants"; -import { EmailValidator } from "../validators/email.validator"; +import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms'; +import { ApplicationType } from '../enums-list'; +import { POSTAL_CODE } from '../regex.constants'; +import { EmailValidator } from '../validators/email.validator'; export class AuthInfoHelper { - postalRegex = POSTAL_CODE; - public setupFormGroup(fb: FormBuilder, form_type: ApplicationType): FormGroup { + postalRegex = POSTAL_CODE; + public setupFormGroup(fb: FormBuilder, form_type: ApplicationType): FormGroup { + let group = { + approvedAuthorityNotification: ['', Validators.requiredTrue], + readAndUnderstoodTermsAndConditions: ['', Validators.requiredTrue], + signName: ['', Validators.required], + signature: ['', Validators.required], + allowCvapStaffSharing: [0], + authorizedPerson: fb.array([]), + authorizedPersonAuthorizesDiscussion: [''], + authorizedPersonSignature: [''] + }; - let group = { - approvedAuthorityNotification: ['', Validators.requiredTrue], - readAndUnderstoodTermsAndConditions: ['', Validators.requiredTrue], - signName: ['', Validators.required], - signature: ['', Validators.required], - allowCvapStaffSharing: [0], - authorizedPerson: fb.array([]), - authorizedPersonAuthorizesDiscussion: [''], - authorizedPersonSignature: [''], - }; + return fb.group(group); + } - return fb.group(group); - } - - createAuthorizedPerson(fb: FormBuilder): FormGroup { - return fb.group({ - providerType: ['', Validators.required], - authorizedPersonFirstName: [''], - authorizedPersonLastName: [''], - authorizedPersonPhoneNumber: [''], - authorizedPersonEmail: ['', [Validators.email]], - authorizedPersonAgencyAddress: fb.group({ - line1: [''], - line2: [''], - city: [''], - postalCode: ['', [Validators.pattern(this.postalRegex)]], // - province: [{ value: 'British Columbia', disabled: false }], - country: [{ value: 'Canada', disabled: false }], - }), - authorizedPersonRelationship: [''], - authorizedPersonRelationshipOther: [''], - authorizedPersonAgencyName: [''], - }); - } + createAuthorizedPerson(fb: FormBuilder): FormGroup { + return fb.group({ + providerType: ['', Validators.required], + authorizedPersonFirstName: [''], + authorizedPersonLastName: [''], + authorizedPersonPhoneNumber: [''], + authorizedPersonEmail: ['', [Validators.email]], + authorizedPersonAgencyAddress: fb.group({ + line1: [''], + line2: [''], + city: [''], + postalCode: ['', [Validators.pattern(this.postalRegex)]], // + province: [{ value: 'British Columbia', disabled: false }], + country: [{ value: 'Canada', disabled: false }] + }), + authorizedPersonRelationship: [''], + authorizedPersonRelationshipOther: [''], + authorizedPersonAgencyName: [''] + }); + } } diff --git a/vsd-app/ClientApp/src/app/shared/cancel-dialog/cancel-dialog.component.ts b/vsd-app/ClientApp/src/app/shared/cancel-dialog/cancel-dialog.component.ts index a1e99a20..7714611e 100644 --- a/vsd-app/ClientApp/src/app/shared/cancel-dialog/cancel-dialog.component.ts +++ b/vsd-app/ClientApp/src/app/shared/cancel-dialog/cancel-dialog.component.ts @@ -7,15 +7,14 @@ import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; templateUrl: './cancel-dialog.component.html' }) export class CancelApplicationDialog implements OnInit { - applicationType: string; constructor( public dialogRef: MatDialogRef, private router: Router, private route: ActivatedRoute, - @Inject(MAT_DIALOG_DATA) public data: any) { - } + @Inject(MAT_DIALOG_DATA) public data: any + ) {} closeMe(): void { this.dialogRef.close(false); diff --git a/vsd-app/ClientApp/src/app/shared/crime-information/crime-information.component.ts b/vsd-app/ClientApp/src/app/shared/crime-information/crime-information.component.ts index d47470ba..9a64bccd 100644 --- a/vsd-app/ClientApp/src/app/shared/crime-information/crime-information.component.ts +++ b/vsd-app/ClientApp/src/app/shared/crime-information/crime-information.component.ts @@ -1,17 +1,24 @@ -import { OnInit, Component, Input, OnDestroy } from "@angular/core"; -import { FormBase } from "../form-base"; -import { MatDialogConfig, MatDialog, DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS, MatDatepickerInputEvent } from "@angular/material"; -import { FormArray, FormGroup, Validators, FormBuilder, ControlContainer, FormControl } from "@angular/forms"; -import { SignPadDialog } from "../../sign-dialog/sign-dialog.component"; -import { MomentDateAdapter } from "@angular/material-moment-adapter"; -import { MY_FORMATS, ApplicationType, CRMBoolean, CRMMultiBoolean } from "../enums-list"; +import { OnInit, Component, Input, OnDestroy } from '@angular/core'; +import { FormBase } from '../form-base'; +import { + MatDialogConfig, + MatDialog, + DateAdapter, + MAT_DATE_LOCALE, + MAT_DATE_FORMATS, + MatDatepickerInputEvent +} from '@angular/material'; +import { FormArray, FormGroup, Validators, FormBuilder, ControlContainer, FormControl } from '@angular/forms'; +import { SignPadDialog } from '../../sign-dialog/sign-dialog.component'; +import { MomentDateAdapter } from '@angular/material-moment-adapter'; +import { MY_FORMATS, ApplicationType, CRMBoolean, CRMMultiBoolean } from '../enums-list'; import * as moment from 'moment'; -import { CrimeInfoHelper } from "./crime-information.helper"; +import { CrimeInfoHelper } from './crime-information.helper'; import { config } from '../../../config'; -import { Subscription } from "rxjs"; -import { AddressHelper } from "../address/address.helper"; -import { iLookupData } from "../../interfaces/lookup-data.interface"; -import { LookupService } from "../../services/lookup.service"; +import { Subscription } from 'rxjs'; +import { AddressHelper } from '../address/address.helper'; +import { iLookupData } from '../../interfaces/lookup-data.interface'; +import { LookupService } from '../../services/lookup.service'; @Component({ selector: 'app-crime-information', @@ -22,8 +29,8 @@ import { LookupService } from "../../services/lookup.service"; // application's root module. We provide it at the component level here, due to limitations of // our example generation script. { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, - { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }, - ], + { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS } + ] }) export class CrimeInformationComponent extends FormBase implements OnInit, OnDestroy { @Input() formType: number; @@ -78,21 +85,24 @@ export class CrimeInformationComponent extends FormBase implements OnInit, OnDes cityList: string[] = []; policeForceList: string[] = []; courtList: string[] = []; - crimeInjuriesLabel: string = "Please specify any injuries, physical or psychological, you sustained as a result of the crime (e.g. bruised leg, broken wrist, sleeplessness). (Maximum 750 characters)"; + crimeInjuriesLabel: string = + 'Please specify any injuries, physical or psychological, you sustained as a result of the crime (e.g. bruised leg, broken wrist, sleeplessness). (Maximum 750 characters)'; addressHelper = new AddressHelper(); constructor( private controlContainer: ControlContainer, private matDialog: MatDialog, private fb: FormBuilder, - public lookupService: LookupService, + public lookupService: LookupService ) { super(); } ngOnInit() { this.form = this.controlContainer.control; - setTimeout(() => { this.form.markAsTouched(); }, 0); + setTimeout(() => { + this.form.markAsTouched(); + }, 0); // console.log("crime info component"); // console.log(this.form); @@ -100,7 +110,8 @@ export class CrimeInformationComponent extends FormBase implements OnInit, OnDes this.showRemovePoliceReport = this.policeReportItems.length > 1; if (this.formType === ApplicationType.IFM_Application) { - this.crimeInjuriesLabel = "Please specify any psychological injuries you sustained as a result of the crime (e.g. anxiety, sleeplessness)"; + this.crimeInjuriesLabel = + 'Please specify any psychological injuries you sustained as a result of the crime (e.g. anxiety, sleeplessness)'; } for (let i = 0; i < this.policeReportItems.length; ++i) { @@ -113,23 +124,21 @@ export class CrimeInformationComponent extends FormBase implements OnInit, OnDes let birthdate = this.form.parent.get('personalInformation.birthDate').value; if (birthdate && moment(birthdate).isAfter(startDate)) { this.showCrimeDateWarning = true; - } - else { + } else { this.showCrimeDateWarning = false; } this.courtFileItems = this.form.get('courtFiles') as FormArray; this.showRemoveCourtInfo = this.courtFileItems.length > 1; - this.wasReportMadeToPoliceSubscription = this.form.get('wasReportMadeToPolice').valueChanges.subscribe(value => { + this.wasReportMadeToPoliceSubscription = this.form.get('wasReportMadeToPolice').valueChanges.subscribe((value) => { let noPoliceReportIdentification = this.form.get('noPoliceReportIdentification'); if (value === CRMMultiBoolean.True) { this.addPoliceReport(); noPoliceReportIdentification.clearValidators(); noPoliceReportIdentification.setErrors(null); noPoliceReportIdentification.setValue(''); - } - else { + } else { this.removeAllPoliceReports(); noPoliceReportIdentification.setValidators([Validators.required]); @@ -138,63 +147,61 @@ export class CrimeInformationComponent extends FormBase implements OnInit, OnDes noPoliceReportIdentification.updateValueAndValidity(); }); - this.applyToCourtForMoneyFromOffenderSubscription = this.form.get('racafInformation.applyToCourtForMoneyFromOffender').valueChanges.subscribe(value => { - if (value === CRMMultiBoolean.True) { - this.applyToCourtOrLegalYes(); - } - else { - this.applyToCourtNo(); - } - }); + this.applyToCourtForMoneyFromOffenderSubscription = this.form + .get('racafInformation.applyToCourtForMoneyFromOffender') + .valueChanges.subscribe((value) => { + if (value === CRMMultiBoolean.True) { + this.applyToCourtOrLegalYes(); + } else { + this.applyToCourtNo(); + } + }); - this.willBeTakingLegalActionSubscription = this.form.get('racafInformation.willBeTakingLegalAction').valueChanges.subscribe(value => { - if (value === CRMMultiBoolean.True) { - this.applyToCourtOrLegalYes(); - } - else { - let doYouHaveALawyerControl = this.form.get('racafInformation.haveLawyer'); - doYouHaveALawyerControl.patchValue(''); - this.haveLawyerChange(false); - this.legalChangesNo(); - } - }); + this.willBeTakingLegalActionSubscription = this.form + .get('racafInformation.willBeTakingLegalAction') + .valueChanges.subscribe((value) => { + if (value === CRMMultiBoolean.True) { + this.applyToCourtOrLegalYes(); + } else { + let doYouHaveALawyerControl = this.form.get('racafInformation.haveLawyer'); + doYouHaveALawyerControl.patchValue(''); + this.haveLawyerChange(false); + this.legalChangesNo(); + } + }); - this.offenderBeenChargedSubscription = this.form.get('offenderBeenCharged').valueChanges.subscribe(value => { + this.offenderBeenChargedSubscription = this.form.get('offenderBeenCharged').valueChanges.subscribe((value) => { if (value === CRMMultiBoolean.True) { // Yes this.offenderBeenChargedYes(); - } - else { + } else { // No or Unknown this.offenderBeenChargedNo(); } }); - this.haveYouSuedOffenderSubscription = this.form.get('haveYouSuedOffender').valueChanges.subscribe(value => { + this.haveYouSuedOffenderSubscription = this.form.get('haveYouSuedOffender').valueChanges.subscribe((value) => { if (value === CRMBoolean.True) { let intendToSue = this.form.get('intendToSueOffender'); this.clearControlValidators(intendToSue); intendToSue.patchValue(''); this.suedOrIntendToSueYes(); - } - else if (value === CRMBoolean.False) { + } else if (value === CRMBoolean.False) { this.suedNo(); } }); - this.intendToSueOffenderSubscription = this.form.get('intendToSueOffender').valueChanges.subscribe(value => { + this.intendToSueOffenderSubscription = this.form.get('intendToSueOffender').valueChanges.subscribe((value) => { if (value === CRMMultiBoolean.True || value === CRMMultiBoolean.Undecided) { this.suedOrIntendToSueYes(); - } - else if (value === CRMMultiBoolean.False) { + } else if (value === CRMMultiBoolean.False) { this.intendToSueNo(); } }); if (this.lookupData.courts && this.lookupData.courts.length > 0) { - this.courtList = this.lookupData.courts.map(c => c.vsd_name); - } - else { + this.courtList = this.lookupData.courts.map((c) => c.vsd_name); + } else { this.lookupService.getCourts().subscribe((res) => { this.lookupData.courts = res.value; if (this.lookupData.courts) { @@ -202,29 +209,27 @@ export class CrimeInformationComponent extends FormBase implements OnInit, OnDes return a.vsd_name.localeCompare(b.vsd_name); }); } - this.courtList = this.lookupData.courts.map(c => c.vsd_name); + this.courtList = this.lookupData.courts.map((c) => c.vsd_name); }); } if (this.lookupData.police_detachments && this.lookupData.police_detachments.length > 0) { - this.policeForceList = this.lookupData.police_detachments.map(pd => pd.vsd_name); - } - else { + this.policeForceList = this.lookupData.police_detachments.map((pd) => pd.vsd_name); + } else { this.lookupService.getPoliceDetachments().subscribe((res) => { this.lookupData.police_detachments = res.value; if (this.lookupData.police_detachments) { this.lookupData.police_detachments.sort(function (a, b) { return a.vsd_name.localeCompare(b.vsd_name); }); - this.policeForceList = this.lookupData.police_detachments.map(pd => pd.vsd_name); + this.policeForceList = this.lookupData.police_detachments.map((pd) => pd.vsd_name); } }); } if (this.lookupData.cities && this.lookupData.cities.length > 0) { - this.cityList = this.lookupData.cities.map(c => c.vsd_name); - } - else { + this.cityList = this.lookupData.cities.map((c) => c.vsd_name); + } else { this.lookupService.getCitiesByProvince(config.canada_crm_id, config.bc_crm_id).subscribe((res) => { this.lookupData.cities = res.value; if (this.lookupData.cities) { @@ -232,14 +237,15 @@ export class CrimeInformationComponent extends FormBase implements OnInit, OnDes return a.vsd_name.localeCompare(b.vsd_name); }); } - this.cityList = this.lookupData.cities.map(c => c.vsd_name); + this.cityList = this.lookupData.cities.map((c) => c.vsd_name); }); } } ngOnDestroy() { if (this.wasReportMadeToPoliceSubscription) this.wasReportMadeToPoliceSubscription.unsubscribe(); - if (this.applyToCourtForMoneyFromOffenderSubscription) this.applyToCourtForMoneyFromOffenderSubscription.unsubscribe(); + if (this.applyToCourtForMoneyFromOffenderSubscription) + this.applyToCourtForMoneyFromOffenderSubscription.unsubscribe(); if (this.willBeTakingLegalActionSubscription) this.willBeTakingLegalActionSubscription.unsubscribe(); if (this.haveYouSuedOffenderSubscription) this.haveYouSuedOffenderSubscription.unsubscribe(); if (this.intendToSueOffenderSubscription) this.intendToSueOffenderSubscription.unsubscribe(); @@ -266,7 +272,7 @@ export class CrimeInformationComponent extends FormBase implements OnInit, OnDes this.showAddPoliceReport = this.policeReportItems.length < 5; this.showRemovePoliceReport = this.policeReportItems.length > 1; - this.policeReportMinDates.push(null) + this.policeReportMinDates.push(null); } removePoliceReport(index: number): void { @@ -319,8 +325,7 @@ export class CrimeInformationComponent extends FormBase implements OnInit, OnDes if (willBeTakingLegal === 100000000) { this.setControlValidators(this.signName, [Validators.required]); this.setControlValidators(this.signature, [Validators.required]); - } - else { + } else { this.signName.patchValue(''); this.signature.patchValue(''); this.clearControlValidators(this.signName); @@ -335,8 +340,7 @@ export class CrimeInformationComponent extends FormBase implements OnInit, OnDes if (applyToCourt === 100000000) { this.setControlValidators(this.signName, [Validators.required]); this.setControlValidators(this.signature, [Validators.required]); - } - else { + } else { this.signName.patchValue(''); this.signature.patchValue(''); this.clearControlValidators(this.signName); @@ -347,13 +351,15 @@ export class CrimeInformationComponent extends FormBase implements OnInit, OnDes haveLawyerChange(val: boolean) { if (!val) { this.form.get('racafInformation.lawyerOrFirmName').patchValue(''); - this.addressHelper.clearAddress(this.form, 'racafInformation.lawyerAddress') + this.addressHelper.clearAddress(this.form, 'racafInformation.lawyerAddress'); } } suedOrIntendToSueYes(): void { this.willBeTakingLegalAction = this.form.get('racafInformation.willBeTakingLegalAction') as FormControl; - this.applyToCourtForMoneyFromOffender = this.form.get('racafInformation.applyToCourtForMoneyFromOffender') as FormControl; + this.applyToCourtForMoneyFromOffender = this.form.get( + 'racafInformation.applyToCourtForMoneyFromOffender' + ) as FormControl; this.setControlValidators(this.willBeTakingLegalAction, [Validators.required]); this.setControlValidators(this.applyToCourtForMoneyFromOffender, [Validators.required]); } @@ -362,12 +368,13 @@ export class CrimeInformationComponent extends FormBase implements OnInit, OnDes let intendToSue = this.form.get('intendToSueOffender') as FormControl; this.setControlValidators(intendToSue, [Validators.required]); this.willBeTakingLegalAction = this.form.get('racafInformation.willBeTakingLegalAction') as FormControl; - this.applyToCourtForMoneyFromOffender = this.form.get('racafInformation.applyToCourtForMoneyFromOffender') as FormControl; + this.applyToCourtForMoneyFromOffender = this.form.get( + 'racafInformation.applyToCourtForMoneyFromOffender' + ) as FormControl; if (intendToSue.value === CRMMultiBoolean.True || intendToSue.value === CRMMultiBoolean.Undecided) { this.setControlValidators(this.willBeTakingLegalAction, [Validators.required]); this.setControlValidators(this.applyToCourtForMoneyFromOffender, [Validators.required]); - } - else { + } else { this.clearControlValidators(this.willBeTakingLegalAction); this.clearControlValidators(this.applyToCourtForMoneyFromOffender); this.willBeTakingLegalAction.patchValue(''); @@ -385,7 +392,9 @@ export class CrimeInformationComponent extends FormBase implements OnInit, OnDes intendToSueNo(): void { this.willBeTakingLegalAction = this.form.get('racafInformation.willBeTakingLegalAction') as FormControl; - this.applyToCourtForMoneyFromOffender = this.form.get('racafInformation.applyToCourtForMoneyFromOffender') as FormControl; + this.applyToCourtForMoneyFromOffender = this.form.get( + 'racafInformation.applyToCourtForMoneyFromOffender' + ) as FormControl; this.clearControlValidators(this.willBeTakingLegalAction); this.clearControlValidators(this.applyToCourtForMoneyFromOffender); this.willBeTakingLegalAction.patchValue(''); @@ -413,14 +422,12 @@ export class CrimeInformationComponent extends FormBase implements OnInit, OnDes const dialogRef = this.matDialog.open(SignPadDialog, dialogConfig); dialogRef.afterClosed().subscribe( - data => { + (data) => { var patchObject = {}; patchObject[control] = data; - this.form.get(group).patchValue( - patchObject - ); + this.form.get(group).patchValue(patchObject); }, - err => console.log(err) + (err) => console.log(err) ); } @@ -438,13 +445,14 @@ export class CrimeInformationComponent extends FormBase implements OnInit, OnDes this.validateCrimePeriodWithinOneYear(); - this.form.get('overOneYearFromCrime').patchValue(this.showWhyDidYouNotApplySooner ? CRMBoolean.True : CRMBoolean.False); + this.form + .get('overOneYearFromCrime') + .patchValue(this.showWhyDidYouNotApplySooner ? CRMBoolean.True : CRMBoolean.False); let birthdate = this.form.parent.get('personalInformation.birthDate').value; if (birthdate && moment(birthdate).isAfter(startDate)) { this.showCrimeDateWarning = true; - } - else { + } else { this.showCrimeDateWarning = false; } } @@ -456,15 +464,16 @@ export class CrimeInformationComponent extends FormBase implements OnInit, OnDes let crimePeriodEndDate = startDate; if (endDate) { crimePeriodEndDate = endDate; - } - else if (this.form.get('whenDidCrimeOccur').value === true || this.form.get('unsureOfCrimeDates').value === true) { + } else if ( + this.form.get('whenDidCrimeOccur').value === true || + this.form.get('unsureOfCrimeDates').value === true + ) { crimePeriodEndDate = null; } if (crimePeriodEndDate) { this.showWhyDidYouNotApplySooner = moment(crimePeriodEndDate).isBefore(this.oneYearAgo); - } - else { + } else { this.showWhyDidYouNotApplySooner = false; } } @@ -475,8 +484,7 @@ export class CrimeInformationComponent extends FormBase implements OnInit, OnDes if (this.form.get('whenDidCrimeOccur').value) { this.setControlValidators(crimePeriodEndControl, [Validators.required]); - } - else if (!unsureOfCrimeDatesControl.value) { + } else if (!unsureOfCrimeDatesControl.value) { crimePeriodEndControl.patchValue(null); this.clearControlValidators(crimePeriodEndControl); } @@ -490,8 +498,7 @@ export class CrimeInformationComponent extends FormBase implements OnInit, OnDes let whenDidCrimeOccurControl = this.form.get('whenDidCrimeOccur'); if (unsureOfCrimeDatesControl.value) { this.setControlValidators(crimePeriodEndControl, [Validators.required]); - } - else if (!whenDidCrimeOccurControl.value) { + } else if (!whenDidCrimeOccurControl.value) { crimePeriodEndControl.patchValue(null); this.clearControlValidators(crimePeriodEndControl); } @@ -521,15 +528,12 @@ export class CrimeInformationComponent extends FormBase implements OnInit, OnDes if (thisReport.get('policeReportedMultipleTimes').value) { thisEndDateControl.patchValue(null); this.clearControlValidators(thisEndDateControl); - } - else { + } else { this.setControlValidators(thisEndDateControl, [Validators.required]); } } - policeForceSelected(index: number) { - - } + policeForceSelected(index: number) {} applyToCourtForMoneyFromOffenderChange() { let applyToCourtForMoneyFromOffenderControl = this.form.get('racafInformation.applyToCourtForMoneyFromOffender'); diff --git a/vsd-app/ClientApp/src/app/shared/crime-information/crime-information.helper.ts b/vsd-app/ClientApp/src/app/shared/crime-information/crime-information.helper.ts index a3e28bcd..ac80b187 100644 --- a/vsd-app/ClientApp/src/app/shared/crime-information/crime-information.helper.ts +++ b/vsd-app/ClientApp/src/app/shared/crime-information/crime-information.helper.ts @@ -1,109 +1,109 @@ -import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms"; -import { ApplicationType } from "../enums-list"; -import { POSTAL_CODE } from "../regex.constants"; +import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms'; +import { ApplicationType } from '../enums-list'; +import { POSTAL_CODE } from '../regex.constants'; export class CrimeInfoHelper { - postalRegex = POSTAL_CODE; - public setupFormGroup(fb: FormBuilder, form_type: ApplicationType): FormGroup { - let group = { - typeOfCrime: ['', Validators.required], + postalRegex = POSTAL_CODE; + public setupFormGroup(fb: FormBuilder, form_type: ApplicationType): FormGroup { + let group = { + typeOfCrime: ['', Validators.required], - unsureOfCrimeDates: [false], - whenDidCrimeOccur: [''], - crimePeriodStart: ['', Validators.required], - crimePeriodEnd: [''], - overOneYearFromCrime: [''], - whyDidYouNotApplySooner: [''], + unsureOfCrimeDates: [false], + whenDidCrimeOccur: [''], + crimePeriodStart: ['', Validators.required], + crimePeriodEnd: [''], + overOneYearFromCrime: [''], + whyDidYouNotApplySooner: [''], - crimeLocations: fb.array([this.createCrimeLocationItem(fb)]), - crimeDetails: ['', Validators.required], - crimeInjuries: ['', Validators.required], - documents: fb.array([]), + crimeLocations: fb.array([this.createCrimeLocationItem(fb)]), + crimeDetails: ['', Validators.required], + crimeInjuries: ['', Validators.required], + documents: fb.array([]), - wasReportMadeToPolice: [0, [Validators.required, Validators.min(100000000), Validators.max(100000002)]], + wasReportMadeToPolice: [0, [Validators.required, Validators.min(100000000), Validators.max(100000002)]], - policeReports: fb.array([]), - noPoliceReportIdentification: [''], + policeReports: fb.array([]), + noPoliceReportIdentification: [''], - moreThanOneOffender: [false], - additionalOffenders: fb.array([]), + moreThanOneOffender: [false], + additionalOffenders: fb.array([]), - offenderFirstName: [''], - offenderMiddleName: [''], - offenderLastName: [''], - offenderRelationship: [''], - offenderBeenCharged: [0, [Validators.required, Validators.min(100000000), Validators.max(100000002)]], + offenderFirstName: [''], + offenderMiddleName: [''], + offenderLastName: [''], + offenderRelationship: [''], + offenderBeenCharged: [0, [Validators.required, Validators.min(100000000), Validators.max(100000002)]], - showAddMoreOffenders: [false], + showAddMoreOffenders: [false], - courtFiles: fb.array([]), + courtFiles: fb.array([]), - haveYouSuedOffender: [0, [Validators.required, Validators.min(100000000), Validators.max(100000001)]], - intendToSueOffender: [null], + haveYouSuedOffender: [0, [Validators.required, Validators.min(100000000), Validators.max(100000001)]], + intendToSueOffender: [null], - racafInformation: this.createRACAFInformation(fb), - }; + racafInformation: this.createRACAFInformation(fb) + }; - if (form_type === ApplicationType.IFM_Application || form_type === ApplicationType.Witness_Application) { - group['victimDeceasedFromCrime'] = ['', Validators.required]; - group['dateOfDeath'] = ['']; - } - return fb.group(group); - } - - createRACAFInformation(fb: FormBuilder): FormGroup { - return fb.group({ - applyToCourtForMoneyFromOffender: [''], - expensesRequested: [''], - expensesAwarded: [null], - expensesReceived: [null], - willBeTakingLegalAction: [''], - haveLawyer: [null, [Validators.min(100000000), Validators.max(100000001)]], - lawyerOrFirmName: [''], - lawyerAddress: fb.group({ - line1: [''], - line2: [''], - city: [''], - postalCode: ['', [Validators.pattern(this.postalRegex)]], - province: [{ value: 'British Columbia', disabled: false }], - country: [{ value: 'Canada', disabled: false }], - }), - signName: [null], - signature: [null], - }) - } - - createCrimeLocationItem(fb: FormBuilder): FormGroup { - return fb.group({ - location: ['', Validators.required] - }); - } - - createPoliceReport(fb: FormBuilder): FormGroup { - return fb.group({ - policeDetachment: [null, [Validators.required]], - policeDetachmentOther: [''], - policeFileNumber: [''], - investigatingOfficer: [''], - reportStartDate: [''], - reportEndDate: [''], - policeReportedMultipleTimes: [''] - }); - } - - createCourtInfoItem(fb: FormBuilder): FormGroup { - return fb.group({ - courtFileNumber: [''], - courtLocation: ['', [Validators.required]] - }); - } - - createAdditionalOffender(fb: FormBuilder): FormGroup { - return fb.group({ - firstName: [''], - middleName: [''], - lastName: [''], - relationship: [''], - }); + if (form_type === ApplicationType.IFM_Application || form_type === ApplicationType.Witness_Application) { + group['victimDeceasedFromCrime'] = ['', Validators.required]; + group['dateOfDeath'] = ['']; } + return fb.group(group); + } + + createRACAFInformation(fb: FormBuilder): FormGroup { + return fb.group({ + applyToCourtForMoneyFromOffender: [''], + expensesRequested: [''], + expensesAwarded: [null], + expensesReceived: [null], + willBeTakingLegalAction: [''], + haveLawyer: [null, [Validators.min(100000000), Validators.max(100000001)]], + lawyerOrFirmName: [''], + lawyerAddress: fb.group({ + line1: [''], + line2: [''], + city: [''], + postalCode: ['', [Validators.pattern(this.postalRegex)]], + province: [{ value: 'British Columbia', disabled: false }], + country: [{ value: 'Canada', disabled: false }] + }), + signName: [null], + signature: [null] + }); + } + + createCrimeLocationItem(fb: FormBuilder): FormGroup { + return fb.group({ + location: ['', Validators.required] + }); + } + + createPoliceReport(fb: FormBuilder): FormGroup { + return fb.group({ + policeDetachment: [null, [Validators.required]], + policeDetachmentOther: [''], + policeFileNumber: [''], + investigatingOfficer: [''], + reportStartDate: [''], + reportEndDate: [''], + policeReportedMultipleTimes: [''] + }); + } + + createCourtInfoItem(fb: FormBuilder): FormGroup { + return fb.group({ + courtFileNumber: [''], + courtLocation: ['', [Validators.required]] + }); + } + + createAdditionalOffender(fb: FormBuilder): FormGroup { + return fb.group({ + firstName: [''], + middleName: [''], + lastName: [''], + relationship: [''] + }); + } } diff --git a/vsd-app/ClientApp/src/app/shared/date-field/date-field.component.ts b/vsd-app/ClientApp/src/app/shared/date-field/date-field.component.ts index f700aa74..1a7ae924 100644 --- a/vsd-app/ClientApp/src/app/shared/date-field/date-field.component.ts +++ b/vsd-app/ClientApp/src/app/shared/date-field/date-field.component.ts @@ -3,73 +3,79 @@ import { AbstractControl } from '@angular/forms'; import * as moment from 'moment'; @Component({ - selector: 'app-date-field', - templateUrl: './date-field.component.html', - styleUrls: ['./date-field.component.scss'] + selector: 'app-date-field', + templateUrl: './date-field.component.html', + styleUrls: ['./date-field.component.scss'] }) export class DateFieldComponent implements OnInit { - @Input() control: AbstractControl; - @Input() max: Date; - @Input() min: Date; - @Input() disabled: boolean; - dayList = []; - yearList = []; + @Input() control: AbstractControl; + @Input() max: Date; + @Input() min: Date; + @Input() disabled: boolean; + dayList = []; + yearList = []; - day = 0; - month = -1; - year = 0; + day = 0; + month = -1; + year = 0; - currentYear = new Date().getFullYear(); + currentYear = new Date().getFullYear(); - constructor() { } + constructor() {} - ngOnInit() { - let date: moment.Moment = this.control.value; - if (date) { - this.year = date.year(); - this.month = date.month(); - this.day = date.date(); - } - - for (let i = 1; i <= 31; ++i) { - this.dayList.push(i); - } + ngOnInit() { + let date: moment.Moment = this.control.value; + if (date) { + this.year = date.year(); + this.month = date.month(); + this.day = date.date(); + } - for (let i = 0; i < 120; ++i) { - this.yearList.push(this.currentYear - i); - } + for (let i = 1; i <= 31; ++i) { + this.dayList.push(i); } - output() { - if (this.day == 0 || this.month == -1 || this.year == 0) { - this.control.patchValue(null); - return; - } + for (let i = 0; i < 120; ++i) { + this.yearList.push(this.currentYear - i); + } + } - this.control.markAsTouched(); + output() { + if (this.day == 0 || this.month == -1 || this.year == 0) { + this.control.patchValue(null); + return; + } - let hasMinError = false; - let hasMaxError = false; + this.control.markAsTouched(); - let date = moment(new Date(this.year, this.month, this.day)); - if (this.min) { - if (date.isBefore(moment(this.min))) { - hasMinError = true; - setTimeout(() => { this.control.setErrors({ 'incorrect': true }); }, 0); - } - } + let hasMinError = false; + let hasMaxError = false; - if (this.max) { - if (date.isAfter(moment(this.max))) { - hasMaxError = true; - setTimeout(() => { this.control.setErrors({ 'incorrect': true }); }, 0); - } - } + let date = moment(new Date(this.year, this.month, this.day)); + if (this.min) { + if (date.isBefore(moment(this.min))) { + hasMinError = true; + setTimeout(() => { + this.control.setErrors({ incorrect: true }); + }, 0); + } + } - if (!hasMinError && !hasMaxError) { - setTimeout(() => { this.control.setErrors(null); }, 0); - } + if (this.max) { + if (date.isAfter(moment(this.max))) { + hasMaxError = true; + setTimeout(() => { + this.control.setErrors({ incorrect: true }); + }, 0); + } + } - this.control.patchValue(date); + if (!hasMinError && !hasMaxError) { + setTimeout(() => { + this.control.setErrors(null); + }, 0); } -} \ No newline at end of file + + this.control.patchValue(date); + } +} diff --git a/vsd-app/ClientApp/src/app/shared/declaration-information/declaration-information.component.scss b/vsd-app/ClientApp/src/app/shared/declaration-information/declaration-information.component.scss index c62175b8..14fb6d92 100644 --- a/vsd-app/ClientApp/src/app/shared/declaration-information/declaration-information.component.scss +++ b/vsd-app/ClientApp/src/app/shared/declaration-information/declaration-information.component.scss @@ -13,4 +13,4 @@ h2, h3 { margin-top: 30px; margin-bottom: 20px; -} \ No newline at end of file +} diff --git a/vsd-app/ClientApp/src/app/shared/declaration-information/declaration-information.component.ts b/vsd-app/ClientApp/src/app/shared/declaration-information/declaration-information.component.ts index b66c8254..63eef69d 100644 --- a/vsd-app/ClientApp/src/app/shared/declaration-information/declaration-information.component.ts +++ b/vsd-app/ClientApp/src/app/shared/declaration-information/declaration-information.component.ts @@ -1,83 +1,81 @@ -import { FormBase } from "../form-base"; -import { OnInit, Component, Input } from "@angular/core"; -import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS, MatDialog, MatDialogConfig } from "@angular/material"; -import { FormGroup, ControlContainer } from "@angular/forms"; -import { MomentDateAdapter } from "@angular/material-moment-adapter"; -import { MY_FORMATS, ApplicationType } from "../enums-list"; -import { SignPadDialog } from "../../sign-dialog/sign-dialog.component"; -import { iLookupData } from "../../interfaces/lookup-data.interface"; -import { LookupService } from "../../services/lookup.service"; +import { FormBase } from '../form-base'; +import { OnInit, Component, Input } from '@angular/core'; +import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS, MatDialog, MatDialogConfig } from '@angular/material'; +import { FormGroup, ControlContainer } from '@angular/forms'; +import { MomentDateAdapter } from '@angular/material-moment-adapter'; +import { MY_FORMATS, ApplicationType } from '../enums-list'; +import { SignPadDialog } from '../../sign-dialog/sign-dialog.component'; +import { iLookupData } from '../../interfaces/lookup-data.interface'; +import { LookupService } from '../../services/lookup.service'; @Component({ - selector: 'app-declaration-information', - templateUrl: './declaration-information.component.html', - styleUrls: ['./declaration-information.component.scss'], - providers: [ - // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your - // application's root module. We provide it at the component level here, due to limitations of - // our example generation script. - { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, - { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }, - ], + selector: 'app-declaration-information', + templateUrl: './declaration-information.component.html', + styleUrls: ['./declaration-information.component.scss'], + providers: [ + // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your + // application's root module. We provide it at the component level here, due to limitations of + // our example generation script. + { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, + { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS } + ] }) export class DeclarationInformationComponent extends FormBase implements OnInit { - @Input() formType: number; - @Input() lookupData: iLookupData; - public form: FormGroup; - ApplicationType = ApplicationType; - eligible_name: string; - cvapEmail: string = ""; + @Input() formType: number; + @Input() lookupData: iLookupData; + public form: FormGroup; + ApplicationType = ApplicationType; + eligible_name: string; + cvapEmail: string = ''; - constructor( - private controlContainer: ControlContainer, - private matDialog: MatDialog, - private lookupService: LookupService - ) { - super(); - } - - ngOnInit() { - this.form = this.controlContainer.control; - setTimeout(() => { this.form.markAsTouched(); }, 0); - // console.log("declaration info component"); - // console.log(this.form); + constructor( + private controlContainer: ControlContainer, + private matDialog: MatDialog, + private lookupService: LookupService + ) { + super(); + } - if (this.formType === ApplicationType.Victim_Application) { - this.eligible_name = "Victims"; - } - if (this.formType === ApplicationType.IFM_Application) { - this.eligible_name = "Immediate Family Members"; - } - if (this.formType === ApplicationType.Witness_Application) { - this.eligible_name = "Witnesses"; - } + ngOnInit() { + this.form = this.controlContainer.control; + setTimeout(() => { + this.form.markAsTouched(); + }, 0); + // console.log("declaration info component"); + // console.log(this.form); - if (this.lookupService.cvapEmail) { - this.cvapEmail = this.lookupService.cvapEmail; - } - else { - this.lookupService.getCVAPEmails().subscribe((res) => { - this.cvapEmail = res.cvapEmail; - }); - } + if (this.formType === ApplicationType.Victim_Application) { + this.eligible_name = 'Victims'; + } + if (this.formType === ApplicationType.IFM_Application) { + this.eligible_name = 'Immediate Family Members'; + } + if (this.formType === ApplicationType.Witness_Application) { + this.eligible_name = 'Witnesses'; } - showSignPad(control): void { - const dialogConfig = new MatDialogConfig(); - dialogConfig.disableClose = true; - dialogConfig.autoFocus = true; - - const dialogRef = this.matDialog.open(SignPadDialog, dialogConfig); - dialogRef.afterClosed().subscribe( - data => { - var patchObject = {}; - patchObject[control] = data; - this.form.patchValue( - patchObject - ); - }, - err => console.log(err) - ); + if (this.lookupService.cvapEmail) { + this.cvapEmail = this.lookupService.cvapEmail; + } else { + this.lookupService.getCVAPEmails().subscribe((res) => { + this.cvapEmail = res.cvapEmail; + }); } + } + + showSignPad(control): void { + const dialogConfig = new MatDialogConfig(); + dialogConfig.disableClose = true; + dialogConfig.autoFocus = true; -} \ No newline at end of file + const dialogRef = this.matDialog.open(SignPadDialog, dialogConfig); + dialogRef.afterClosed().subscribe( + (data) => { + var patchObject = {}; + patchObject[control] = data; + this.form.patchValue(patchObject); + }, + (err) => console.log(err) + ); + } +} diff --git a/vsd-app/ClientApp/src/app/shared/declaration-information/declaration-information.helper.ts b/vsd-app/ClientApp/src/app/shared/declaration-information/declaration-information.helper.ts index 9c942bd2..99ed0a57 100644 --- a/vsd-app/ClientApp/src/app/shared/declaration-information/declaration-information.helper.ts +++ b/vsd-app/ClientApp/src/app/shared/declaration-information/declaration-information.helper.ts @@ -1,15 +1,15 @@ -import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms"; -import { ApplicationType } from "../enums-list"; -import { POSTAL_CODE } from "../regex.constants"; +import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms'; +import { ApplicationType } from '../enums-list'; +import { POSTAL_CODE } from '../regex.constants'; export class DeclarationInfoHelper { - postalRegex = POSTAL_CODE; - public setupFormGroup(fb: FormBuilder, form_type: ApplicationType): FormGroup { - let group = { - declaredAndSigned: ['', Validators.requiredTrue], - signature: ['', Validators.required], - }; + postalRegex = POSTAL_CODE; + public setupFormGroup(fb: FormBuilder, form_type: ApplicationType): FormGroup { + let group = { + declaredAndSigned: ['', Validators.requiredTrue], + signature: ['', Validators.required] + }; - return fb.group(group); - } -} \ No newline at end of file + return fb.group(group); + } +} diff --git a/vsd-app/ClientApp/src/app/shared/dialogs/cancel/cancel.dialog.scss b/vsd-app/ClientApp/src/app/shared/dialogs/cancel/cancel.dialog.scss index 89de3403..183f85a7 100644 --- a/vsd-app/ClientApp/src/app/shared/dialogs/cancel/cancel.dialog.scss +++ b/vsd-app/ClientApp/src/app/shared/dialogs/cancel/cancel.dialog.scss @@ -1,3 +1,3 @@ .mat-dialog-actions { - display: block !important; -} \ No newline at end of file + display: block !important; +} diff --git a/vsd-app/ClientApp/src/app/shared/dialogs/cancel/cancel.dialog.ts b/vsd-app/ClientApp/src/app/shared/dialogs/cancel/cancel.dialog.ts index 211ad4b4..c932af36 100644 --- a/vsd-app/ClientApp/src/app/shared/dialogs/cancel/cancel.dialog.ts +++ b/vsd-app/ClientApp/src/app/shared/dialogs/cancel/cancel.dialog.ts @@ -2,22 +2,21 @@ import { Component, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; @Component({ - selector: 'app-cancel', - templateUrl: 'cancel.dialog.html', - styleUrls: ['./cancel.dialog.scss'], + selector: 'app-cancel', + templateUrl: 'cancel.dialog.html', + styleUrls: ['./cancel.dialog.scss'] }) export class CancelDialog { - type: string = "Application"; - constructor(public dialogRef: MatDialogRef, - @Inject(MAT_DIALOG_DATA) public data: any) { - this.type = data.type || "Application"; - } + type: string = 'Application'; + constructor(public dialogRef: MatDialogRef, @Inject(MAT_DIALOG_DATA) public data: any) { + this.type = data.type || 'Application'; + } - cancel() { - this.dialogRef.close({cancel: true}); - } + cancel() { + this.dialogRef.close({ cancel: true }); + } - closeMe() { - this.dialogRef.close({cancel: false}); - } + closeMe() { + this.dialogRef.close({ cancel: false }); + } } diff --git a/vsd-app/ClientApp/src/app/shared/dialogs/gst-warning/gst-warning.dialog.ts b/vsd-app/ClientApp/src/app/shared/dialogs/gst-warning/gst-warning.dialog.ts index 7a777314..41637153 100644 --- a/vsd-app/ClientApp/src/app/shared/dialogs/gst-warning/gst-warning.dialog.ts +++ b/vsd-app/ClientApp/src/app/shared/dialogs/gst-warning/gst-warning.dialog.ts @@ -3,12 +3,10 @@ import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; @Component({ selector: 'app-gst-warning.dialog', - templateUrl: 'gst-warning.dialog.html', + templateUrl: 'gst-warning.dialog.html' }) export class GSTWarningDialog { - constructor(public dialogRef: MatDialogRef, - @Inject(MAT_DIALOG_DATA) public data: any) { - } + constructor(public dialogRef: MatDialogRef, @Inject(MAT_DIALOG_DATA) public data: any) {} onOkayClick() { this.dialogRef.close(); diff --git a/vsd-app/ClientApp/src/app/shared/dialogs/invoice-instructions/invoice-instructions.dialog.ts b/vsd-app/ClientApp/src/app/shared/dialogs/invoice-instructions/invoice-instructions.dialog.ts index f4122e9f..642bda10 100644 --- a/vsd-app/ClientApp/src/app/shared/dialogs/invoice-instructions/invoice-instructions.dialog.ts +++ b/vsd-app/ClientApp/src/app/shared/dialogs/invoice-instructions/invoice-instructions.dialog.ts @@ -4,23 +4,23 @@ import { LookupService } from '../../../services/lookup.service'; @Component({ selector: 'app-invoice-instructions.dialog', - templateUrl: 'invoice-instructions.dialog.html', + templateUrl: 'invoice-instructions.dialog.html' }) export class InvoiceInstructionsDialog implements OnInit { - cvapEmail: string = ""; - cvapCounsellingEmail: string = ""; + cvapEmail: string = ''; + cvapCounsellingEmail: string = ''; - constructor(public dialogRef: MatDialogRef, + constructor( + public dialogRef: MatDialogRef, private lookupService: LookupService, - @Inject(MAT_DIALOG_DATA) public data: any) { - } + @Inject(MAT_DIALOG_DATA) public data: any + ) {} ngOnInit() { if (this.lookupService.cvapEmail) { this.cvapEmail = this.lookupService.cvapEmail; this.cvapCounsellingEmail = this.lookupService.cvapCounsellingEmail; - } - else { + } else { this.lookupService.getCVAPEmails().subscribe((res) => { this.cvapEmail = res.cvapEmail; this.cvapCounsellingEmail = res.cvapCounsellingEmail; @@ -28,7 +28,6 @@ export class InvoiceInstructionsDialog implements OnInit { } } - onOkayClick() { this.dialogRef.close(); } diff --git a/vsd-app/ClientApp/src/app/shared/dialogs/message-dialog/message.dialog.ts b/vsd-app/ClientApp/src/app/shared/dialogs/message-dialog/message.dialog.ts index 3676bc33..56d85c10 100644 --- a/vsd-app/ClientApp/src/app/shared/dialogs/message-dialog/message.dialog.ts +++ b/vsd-app/ClientApp/src/app/shared/dialogs/message-dialog/message.dialog.ts @@ -3,13 +3,12 @@ import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; @Component({ selector: 'app-message.dialog', - templateUrl: 'message.dialog.html', + templateUrl: 'message.dialog.html' }) export class MessageDialog { title: string; message: string; - constructor(public dialogRef: MatDialogRef, - @Inject(MAT_DIALOG_DATA) public data: any) { + constructor(public dialogRef: MatDialogRef, @Inject(MAT_DIALOG_DATA) public data: any) { this.title = data.title; this.message = data.message; } diff --git a/vsd-app/ClientApp/src/app/shared/employment-information/employment-information.component.ts b/vsd-app/ClientApp/src/app/shared/employment-information/employment-information.component.ts index a8b06025..3257df63 100644 --- a/vsd-app/ClientApp/src/app/shared/employment-information/employment-information.component.ts +++ b/vsd-app/ClientApp/src/app/shared/employment-information/employment-information.component.ts @@ -1,309 +1,304 @@ -import { OnInit, Component, Input, OnDestroy } from "@angular/core"; -import { FormBase } from "../form-base"; -import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS, MatDatepickerInputEvent } from "@angular/material"; -import { FormArray, FormGroup, Validators, FormBuilder, ControlContainer, AbstractControl } from "@angular/forms"; -import { MomentDateAdapter } from "@angular/material-moment-adapter"; -import { MY_FORMATS, ApplicationType, CRMBoolean } from "../enums-list"; +import { OnInit, Component, Input, OnDestroy } from '@angular/core'; +import { FormBase } from '../form-base'; +import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS, MatDatepickerInputEvent } from '@angular/material'; +import { FormArray, FormGroup, Validators, FormBuilder, ControlContainer, AbstractControl } from '@angular/forms'; +import { MomentDateAdapter } from '@angular/material-moment-adapter'; +import { MY_FORMATS, ApplicationType, CRMBoolean } from '../enums-list'; import * as moment from 'moment'; -import { POSTAL_CODE } from "../regex.constants"; -import { COUNTRIES_ADDRESS_2 } from "../address/country-list"; -import { EmploymentInfoHelper } from "./employment-information.helper"; -import { Subscription } from "rxjs"; -import { AddressHelper } from "../address/address.helper"; -import { iLookupData } from "../../interfaces/lookup-data.interface"; +import { POSTAL_CODE } from '../regex.constants'; +import { COUNTRIES_ADDRESS_2 } from '../address/country-list'; +import { EmploymentInfoHelper } from './employment-information.helper'; +import { Subscription } from 'rxjs'; +import { AddressHelper } from '../address/address.helper'; +import { iLookupData } from '../../interfaces/lookup-data.interface'; @Component({ - selector: 'app-employment-information', - templateUrl: './employment-information.component.html', - styleUrls: ['./employment-information.component.scss'], - providers: [ - // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your - // application's root module. We provide it at the component level here, due to limitations of - // our example generation script. - { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, - { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }, - ], + selector: 'app-employment-information', + templateUrl: './employment-information.component.html', + styleUrls: ['./employment-information.component.scss'], + providers: [ + // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your + // application's root module. We provide it at the component level here, due to limitations of + // our example generation script. + { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, + { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS } + ] }) export class EmploymentInformationComponent extends FormBase implements OnInit, OnDestroy { - @Input() formType: number; - @Input() lookupData: iLookupData; - public form: FormGroup; - - postalRegex = POSTAL_CODE; - - countryList = COUNTRIES_ADDRESS_2; - showCurrentlyOffWork: boolean = false; - today = new Date(); - minEndDate: Date; - CRMBoolean = CRMBoolean; - - employers: FormArray; - - employmentInfoHelper = new EmploymentInfoHelper(); - addressHelper = new AddressHelper(); - - employedAtTimeOfCrimeSubscription: Subscription; - atWorkAtTimeOfCrimeSubscription: Subscription; - appliedToWorkSafeBCSubscription: Subscription; - didMissWorkSubscription: Subscription; - areYouStillOffWorkSubscription: Subscription; - loseWagesSubscription: Subscription; - selfEmployedSubscription: Subscription; - sinSubscription: Subscription; - - constructor(private controlContainer: ControlContainer, - private fb: FormBuilder, - ) { - super(); + @Input() formType: number; + @Input() lookupData: iLookupData; + public form: FormGroup; + + postalRegex = POSTAL_CODE; + + countryList = COUNTRIES_ADDRESS_2; + showCurrentlyOffWork: boolean = false; + today = new Date(); + minEndDate: Date; + CRMBoolean = CRMBoolean; + + employers: FormArray; + + employmentInfoHelper = new EmploymentInfoHelper(); + addressHelper = new AddressHelper(); + + employedAtTimeOfCrimeSubscription: Subscription; + atWorkAtTimeOfCrimeSubscription: Subscription; + appliedToWorkSafeBCSubscription: Subscription; + didMissWorkSubscription: Subscription; + areYouStillOffWorkSubscription: Subscription; + loseWagesSubscription: Subscription; + selfEmployedSubscription: Subscription; + sinSubscription: Subscription; + + constructor(private controlContainer: ControlContainer, private fb: FormBuilder) { + super(); + } + + ngOnInit() { + this.form = this.controlContainer.control; + + //wrapping this in a timeout fixes "Expression Changed after it was checked" errors... not ideal, but whatever + setTimeout(() => { + this.form.markAsTouched(); + + if (this.form.parent.get('expenseInformation.haveLostEmploymentIncomeExpenses').value === true) { + let emplaoyedAtTimeOfCrimeControl = this.form.get('wereYouEmployedAtTimeOfCrime'); + let didYouMissWorkDueToCrimeControl = this.form.get('didYouMissWorkDueToCrime'); + emplaoyedAtTimeOfCrimeControl.setValidators([Validators.required]); + emplaoyedAtTimeOfCrimeControl.updateValueAndValidity(); + didYouMissWorkDueToCrimeControl.setValidators([Validators.required]); + didYouMissWorkDueToCrimeControl.updateValueAndValidity(); + } else { + let options = { onlySelf: true, emitEvent: false }; + let emplaoyedAtTimeOfCrimeControl = this.form.get('wereYouEmployedAtTimeOfCrime'); + let didYouMissWorkDueToCrimeControl = this.form.get('didYouMissWorkDueToCrime'); + + emplaoyedAtTimeOfCrimeControl.clearValidators(); + emplaoyedAtTimeOfCrimeControl.setErrors(null, options); + emplaoyedAtTimeOfCrimeControl.updateValueAndValidity(options); + didYouMissWorkDueToCrimeControl.clearValidators(); + didYouMissWorkDueToCrimeControl.setErrors(null, options); + didYouMissWorkDueToCrimeControl.updateValueAndValidity(options); + } + }, 0); + // console.log("employment info"); + // console.log(this.form); + + let endDate = this.form.get('daysWorkMissedEnd').value; + if (endDate) { + this.showCurrentlyOffWork = moment(endDate).isSame(new Date(), 'day'); } - ngOnInit() { - this.form = this.controlContainer.control; - - //wrapping this in a timeout fixes "Expression Changed after it was checked" errors... not ideal, but whatever - setTimeout(() => { - this.form.markAsTouched(); - - if (this.form.parent.get('expenseInformation.haveLostEmploymentIncomeExpenses').value === true) { - let emplaoyedAtTimeOfCrimeControl = this.form.get('wereYouEmployedAtTimeOfCrime'); - let didYouMissWorkDueToCrimeControl = this.form.get('didYouMissWorkDueToCrime'); - emplaoyedAtTimeOfCrimeControl.setValidators([Validators.required]); - emplaoyedAtTimeOfCrimeControl.updateValueAndValidity(); - didYouMissWorkDueToCrimeControl.setValidators([Validators.required]); - didYouMissWorkDueToCrimeControl.updateValueAndValidity(); - } - else { - let options = { onlySelf: true, emitEvent: false }; - let emplaoyedAtTimeOfCrimeControl = this.form.get('wereYouEmployedAtTimeOfCrime'); - let didYouMissWorkDueToCrimeControl = this.form.get('didYouMissWorkDueToCrime'); - - emplaoyedAtTimeOfCrimeControl.clearValidators(); - emplaoyedAtTimeOfCrimeControl.setErrors(null, options); - emplaoyedAtTimeOfCrimeControl.updateValueAndValidity(options); - didYouMissWorkDueToCrimeControl.clearValidators(); - didYouMissWorkDueToCrimeControl.setErrors(null, options); - didYouMissWorkDueToCrimeControl.updateValueAndValidity(options); - } - - }, 0); - // console.log("employment info"); - // console.log(this.form); - - let endDate = this.form.get('daysWorkMissedEnd').value; - if (endDate) { - this.showCurrentlyOffWork = moment(endDate).isSame(new Date(), "day"); - } + this.employedAtTimeOfCrimeSubscription = this.form + .get('wereYouEmployedAtTimeOfCrime') + .valueChanges.subscribe((value) => { + let control = this.form.get('wereYouAtWorkAtTimeOfIncident'); - this.employedAtTimeOfCrimeSubscription = this.form.get('wereYouEmployedAtTimeOfCrime').valueChanges.subscribe((value) => { - let control = this.form.get('wereYouAtWorkAtTimeOfIncident'); - - if (value === CRMBoolean.True) { - this.setControlValidators(control, [Validators.required]); - } - else { - control.patchValue(''); - this.clearControlValidators(control); - } - }); - - this.atWorkAtTimeOfCrimeSubscription = this.form.get('wereYouAtWorkAtTimeOfIncident').valueChanges.subscribe((value) => { - let control = this.form.get('haveYouAppliedToWorkSafe'); - - if (value === CRMBoolean.True) { - this.setControlValidators(control, [Validators.required]); - } - else { - control.patchValue(''); - this.clearControlValidators(control); - } - }); - - this.appliedToWorkSafeBCSubscription = this.form.get('haveYouAppliedToWorkSafe').valueChanges.subscribe((value) => { - let control = this.form.get('workersCompensationClaimNumber'); - - if (value === CRMBoolean.True) { - this.setControlValidators(control, [Validators.required]); - } - else { - control.patchValue(''); - this.clearControlValidators(control); - } - }); - - this.didMissWorkSubscription = this.form.get('didYouMissWorkDueToCrime').valueChanges.subscribe((value) => { - let startDayControl = this.form.get('daysWorkMissedStart'); - let endDayControl = this.form.get('daysWorkMissedEnd'); - let offWorkControl = this.form.get('areYouStillOffWork'); - let loseWageControl = this.form.get('didYouLoseWages'); - - if (value === CRMBoolean.True) { - this.setControlValidators(startDayControl, [Validators.required]); - this.setControlValidators(offWorkControl, [Validators.required]); - this.setControlValidators(loseWageControl, [Validators.required]); - if (this.form.get('areYouStillOffWork').value === CRMBoolean.False) { - this.setControlValidators(endDayControl, [Validators.required]); - } - else { - this.clearControlValidators(endDayControl); - } - } - else { - startDayControl.patchValue(''); - endDayControl.patchValue(''); - offWorkControl.patchValue(''); - loseWageControl.patchValue(''); - this.clearControlValidators(startDayControl); - this.clearControlValidators(endDayControl); - this.clearControlValidators(offWorkControl); - this.clearControlValidators(loseWageControl); - } - }); - - this.areYouStillOffWorkSubscription = this.form.get('areYouStillOffWork').valueChanges.subscribe((value) => { - let endDayControl = this.form.get('daysWorkMissedEnd'); - - if (value === CRMBoolean.False) { - this.setControlValidators(endDayControl, [Validators.required]); - } - else { - endDayControl.patchValue(''); - this.clearControlValidators(endDayControl); - } - }); - - this.loseWagesSubscription = this.form.get('didYouLoseWages').valueChanges.subscribe((value) => { - let control = this.form.get('areYouSelfEmployed'); - let sinControl = this.form.get('sin'); - - - if (value === CRMBoolean.True) { - // this.removeAllEmployers(); - this.showEmployers(); - this.setControlValidators(control, [Validators.required]); - this.setControlValidators(sinControl, [Validators.required]); - } - else { - this.removeAllEmployers(); - control.patchValue(''); - this.clearControlValidators(control); - this.clearControlValidators(sinControl); - } - }); - - this.sinSubscription = this.form.get('sin').valueChanges.subscribe((value) => { - if (value === null) value = ''; - this.form.parent.get('personalInformation').get('sin').patchValue(value); - }); - - this.selfEmployedSubscription = this.form.get('areYouSelfEmployed').valueChanges.subscribe((value) => { - let currentEmployers = this.form.get('employers') as FormArray; - - for (let i = 0; i < currentEmployers.length; ++i) { - let thisEmployer = currentEmployers.controls[i] as FormGroup; - let control = thisEmployer.get('contactable'); - - if (value === CRMBoolean.True) { - // let options = { onlySelf: true, emitEvent: false } - control.patchValue(null); - this.clearControlValidators(control); - } - else { - this.setControlValidators(control, [Validators.required]); - } - } - }); - } - - contactableChange(val: boolean, index: number) { - let currentEmployers = this.form.get('employers') as FormArray; - let thisEmployer = currentEmployers.controls[index] as FormGroup; - - if (thisEmployer) { - let nameControl = thisEmployer.get('employerName'); - let phoneControl = thisEmployer.get('employerPhoneNumber'); - if (val) { - this.setControlValidators(nameControl, [Validators.required]); - this.setControlValidators(phoneControl, [Validators.required]); - this.addressHelper.setAddressAsRequired(thisEmployer, 'employerAddress'); - } - else { - this.clearControlValidators(nameControl); - this.clearControlValidators(phoneControl); - this.addressHelper.clearAddressValidatorsAndErrors(thisEmployer, 'employerAddress'); - } + if (value === CRMBoolean.True) { + this.setControlValidators(control, [Validators.required]); + } else { + control.patchValue(''); + this.clearControlValidators(control); } - } - - ngOnDestroy() { - if (this.employedAtTimeOfCrimeSubscription) this.employedAtTimeOfCrimeSubscription.unsubscribe(); - if (this.atWorkAtTimeOfCrimeSubscription) this.atWorkAtTimeOfCrimeSubscription.unsubscribe(); - if (this.appliedToWorkSafeBCSubscription) this.appliedToWorkSafeBCSubscription.unsubscribe(); - if (this.didMissWorkSubscription) this.didMissWorkSubscription.unsubscribe(); - if (this.areYouStillOffWorkSubscription) this.areYouStillOffWorkSubscription.unsubscribe(); - if (this.loseWagesSubscription) this.loseWagesSubscription.unsubscribe(); - if (this.sinSubscription) this.sinSubscription.unsubscribe(); - if (this.selfEmployedSubscription) this.selfEmployedSubscription.unsubscribe(); - } - - getCountryProperty(country: string, properyName: string): any { - if (!country) country = 'Canada'; - if (!properyName) properyName = 'areaType'; - // return 'Province' by default. - return this.countryList[country][properyName]; - } - showEmployers() { - this.employers = this.form.get('employers') as FormArray; - if (this.employers.length == 0) { - this.employers.push(this.employmentInfoHelper.createEmployerInfo(this.fb)); + }); + + this.atWorkAtTimeOfCrimeSubscription = this.form + .get('wereYouAtWorkAtTimeOfIncident') + .valueChanges.subscribe((value) => { + let control = this.form.get('haveYouAppliedToWorkSafe'); + + if (value === CRMBoolean.True) { + this.setControlValidators(control, [Validators.required]); + } else { + control.patchValue(''); + this.clearControlValidators(control); } + }); + + this.appliedToWorkSafeBCSubscription = this.form.get('haveYouAppliedToWorkSafe').valueChanges.subscribe((value) => { + let control = this.form.get('workersCompensationClaimNumber'); + + if (value === CRMBoolean.True) { + this.setControlValidators(control, [Validators.required]); + } else { + control.patchValue(''); + this.clearControlValidators(control); + } + }); + + this.didMissWorkSubscription = this.form.get('didYouMissWorkDueToCrime').valueChanges.subscribe((value) => { + let startDayControl = this.form.get('daysWorkMissedStart'); + let endDayControl = this.form.get('daysWorkMissedEnd'); + let offWorkControl = this.form.get('areYouStillOffWork'); + let loseWageControl = this.form.get('didYouLoseWages'); + + if (value === CRMBoolean.True) { + this.setControlValidators(startDayControl, [Validators.required]); + this.setControlValidators(offWorkControl, [Validators.required]); + this.setControlValidators(loseWageControl, [Validators.required]); + if (this.form.get('areYouStillOffWork').value === CRMBoolean.False) { + this.setControlValidators(endDayControl, [Validators.required]); + } else { + this.clearControlValidators(endDayControl); + } + } else { + startDayControl.patchValue(''); + endDayControl.patchValue(''); + offWorkControl.patchValue(''); + loseWageControl.patchValue(''); + this.clearControlValidators(startDayControl); + this.clearControlValidators(endDayControl); + this.clearControlValidators(offWorkControl); + this.clearControlValidators(loseWageControl); + } + }); + + this.areYouStillOffWorkSubscription = this.form.get('areYouStillOffWork').valueChanges.subscribe((value) => { + let endDayControl = this.form.get('daysWorkMissedEnd'); + + if (value === CRMBoolean.False) { + this.setControlValidators(endDayControl, [Validators.required]); + } else { + endDayControl.patchValue(''); + this.clearControlValidators(endDayControl); + } + }); + + this.loseWagesSubscription = this.form.get('didYouLoseWages').valueChanges.subscribe((value) => { + let control = this.form.get('areYouSelfEmployed'); + let sinControl = this.form.get('sin'); + + if (value === CRMBoolean.True) { + // this.removeAllEmployers(); + this.showEmployers(); + this.setControlValidators(control, [Validators.required]); + this.setControlValidators(sinControl, [Validators.required]); + } else { + this.removeAllEmployers(); + control.patchValue(''); + this.clearControlValidators(control); + this.clearControlValidators(sinControl); + } + }); + + this.sinSubscription = this.form.get('sin').valueChanges.subscribe((value) => { + if (value === null) value = ''; + this.form.parent.get('personalInformation').get('sin').patchValue(value); + }); + + this.selfEmployedSubscription = this.form.get('areYouSelfEmployed').valueChanges.subscribe((value) => { + let currentEmployers = this.form.get('employers') as FormArray; + + for (let i = 0; i < currentEmployers.length; ++i) { + let thisEmployer = currentEmployers.controls[i] as FormGroup; + let control = thisEmployer.get('contactable'); + + if (value === CRMBoolean.True) { + // let options = { onlySelf: true, emitEvent: false } + control.patchValue(null); + this.clearControlValidators(control); + } else { + this.setControlValidators(control, [Validators.required]); + } + } + }); + } + + contactableChange(val: boolean, index: number) { + let currentEmployers = this.form.get('employers') as FormArray; + let thisEmployer = currentEmployers.controls[index] as FormGroup; + + if (thisEmployer) { + let nameControl = thisEmployer.get('employerName'); + let phoneControl = thisEmployer.get('employerPhoneNumber'); + if (val) { + this.setControlValidators(nameControl, [Validators.required]); + this.setControlValidators(phoneControl, [Validators.required]); + this.addressHelper.setAddressAsRequired(thisEmployer, 'employerAddress'); + } else { + this.clearControlValidators(nameControl); + this.clearControlValidators(phoneControl); + this.addressHelper.clearAddressValidatorsAndErrors(thisEmployer, 'employerAddress'); + } } - addEmployer() { - this.employers = this.form.get('employers') as FormArray; - this.employers.push(this.employmentInfoHelper.createEmployerInfo(this.fb)); - } - removeEmployer(i: number) { - this.employers = this.form.get('employers') as FormArray; - this.employers.removeAt(i); + } + + ngOnDestroy() { + if (this.employedAtTimeOfCrimeSubscription) this.employedAtTimeOfCrimeSubscription.unsubscribe(); + if (this.atWorkAtTimeOfCrimeSubscription) this.atWorkAtTimeOfCrimeSubscription.unsubscribe(); + if (this.appliedToWorkSafeBCSubscription) this.appliedToWorkSafeBCSubscription.unsubscribe(); + if (this.didMissWorkSubscription) this.didMissWorkSubscription.unsubscribe(); + if (this.areYouStillOffWorkSubscription) this.areYouStillOffWorkSubscription.unsubscribe(); + if (this.loseWagesSubscription) this.loseWagesSubscription.unsubscribe(); + if (this.sinSubscription) this.sinSubscription.unsubscribe(); + if (this.selfEmployedSubscription) this.selfEmployedSubscription.unsubscribe(); + } + + getCountryProperty(country: string, properyName: string): any { + if (!country) country = 'Canada'; + if (!properyName) properyName = 'areaType'; + // return 'Province' by default. + return this.countryList[country][properyName]; + } + showEmployers() { + this.employers = this.form.get('employers') as FormArray; + if (this.employers.length == 0) { + this.employers.push(this.employmentInfoHelper.createEmployerInfo(this.fb)); } - removeAllEmployers() { - this.employers = this.form.get('employers') as FormArray; - while (this.employers.length !== 0) { - this.employers.removeAt(0); - } + } + addEmployer() { + this.employers = this.form.get('employers') as FormArray; + this.employers.push(this.employmentInfoHelper.createEmployerInfo(this.fb)); + } + removeEmployer(i: number) { + this.employers = this.form.get('employers') as FormArray; + this.employers.removeAt(i); + } + removeAllEmployers() { + this.employers = this.form.get('employers') as FormArray; + while (this.employers.length !== 0) { + this.employers.removeAt(0); } + } - daysWorkMissedStartChange() { - this.minEndDate = this.form.get('daysWorkMissedStart').value; - //validate that a selected end date is not before the start date - let startDate = moment(this.form.get('daysWorkMissedStart').value); + daysWorkMissedStartChange() { + this.minEndDate = this.form.get('daysWorkMissedStart').value; + //validate that a selected end date is not before the start date + let startDate = moment(this.form.get('daysWorkMissedStart').value); - let endDate = this.form.get('daysWorkMissedEnd').value; - if (endDate && moment(endDate).isBefore(startDate)) { - this.form.get('daysWorkMissedEnd').patchValue(''); - this.form.get('daysWorkMissedEnd').updateValueAndValidity(); - } + let endDate = this.form.get('daysWorkMissedEnd').value; + if (endDate && moment(endDate).isBefore(startDate)) { + this.form.get('daysWorkMissedEnd').patchValue(''); + this.form.get('daysWorkMissedEnd').updateValueAndValidity(); } - - daysWorkMissedEndChange() { - let endDate = moment(this.form.get('daysWorkMissedEnd').value); - this.showCurrentlyOffWork = endDate.isSame(new Date(), "day"); + } + + daysWorkMissedEndChange() { + let endDate = moment(this.form.get('daysWorkMissedEnd').value); + this.showCurrentlyOffWork = endDate.isSame(new Date(), 'day'); + } + + setEmployerPhoneValidators(employer: AbstractControl) { + let phoneMinLength = 10; + let phoneMaxLength = 15; + if ( + employer.get('employerAddress.country').value === 'Canada' || + employer.get('employerAddress.country').value === 'United States of America' + ) { + phoneMinLength = 10; + } else { + phoneMinLength = 8; } - setEmployerPhoneValidators(employer: AbstractControl) { - let phoneMinLength = 10; - let phoneMaxLength = 15; - if (employer.get('employerAddress.country').value === 'Canada' || employer.get('employerAddress.country').value === 'United States of America') { - phoneMinLength = 10; - } - else { - phoneMinLength = 8; - } - - let phoneControl = employer.get('employerPhoneNumber'); - let faxControl = employer.get('employerFax'); - this.setControlValidators(phoneControl, [Validators.minLength(phoneMinLength), Validators.maxLength(phoneMaxLength)]); - this.setControlValidators(faxControl, [Validators.minLength(phoneMinLength), Validators.maxLength(phoneMaxLength)]); - phoneControl.patchValue(phoneControl.value); - faxControl.patchValue(faxControl.value); - } + let phoneControl = employer.get('employerPhoneNumber'); + let faxControl = employer.get('employerFax'); + this.setControlValidators(phoneControl, [ + Validators.minLength(phoneMinLength), + Validators.maxLength(phoneMaxLength) + ]); + this.setControlValidators(faxControl, [Validators.minLength(phoneMinLength), Validators.maxLength(phoneMaxLength)]); + phoneControl.patchValue(phoneControl.value); + faxControl.patchValue(faxControl.value); + } } diff --git a/vsd-app/ClientApp/src/app/shared/employment-information/employment-information.helper.ts b/vsd-app/ClientApp/src/app/shared/employment-information/employment-information.helper.ts index aba686c9..f1507725 100644 --- a/vsd-app/ClientApp/src/app/shared/employment-information/employment-information.helper.ts +++ b/vsd-app/ClientApp/src/app/shared/employment-information/employment-information.helper.ts @@ -1,49 +1,49 @@ -import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms"; -import { ApplicationType } from "../enums-list"; -import { POSTAL_CODE } from "../regex.constants"; +import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms'; +import { ApplicationType } from '../enums-list'; +import { POSTAL_CODE } from '../regex.constants'; export class EmploymentInfoHelper { - postalRegex = POSTAL_CODE; - public setupFormGroup(fb: FormBuilder, form_type: ApplicationType): FormGroup { - let group = { - wereYouEmployedAtTimeOfCrime: [''], //, Validators.required], - wereYouAtWorkAtTimeOfIncident: [''], - haveYouAppliedToWorkSafe: [''], - wsbcClaimNumber: [''], - didYouMissWorkDueToCrime: [''], //, Validators.required], - didYouLoseWages: [''], - sin: ['', [Validators.minLength(9), Validators.maxLength(9)]], - areYouSelfEmployed: [''], - // mayContactEmployer: [''], - haveYouAppliedForWorkersCompensation: [''], - areYouStillOffWork: [''], - daysWorkMissedStart: [''], - daysWorkMissedEnd: [''], - workersCompensationClaimNumber: [''], - employers: fb.array([]), - documents: fb.array([]), - }; + postalRegex = POSTAL_CODE; + public setupFormGroup(fb: FormBuilder, form_type: ApplicationType): FormGroup { + let group = { + wereYouEmployedAtTimeOfCrime: [''], //, Validators.required], + wereYouAtWorkAtTimeOfIncident: [''], + haveYouAppliedToWorkSafe: [''], + wsbcClaimNumber: [''], + didYouMissWorkDueToCrime: [''], //, Validators.required], + didYouLoseWages: [''], + sin: ['', [Validators.minLength(9), Validators.maxLength(9)]], + areYouSelfEmployed: [''], + // mayContactEmployer: [''], + haveYouAppliedForWorkersCompensation: [''], + areYouStillOffWork: [''], + daysWorkMissedStart: [''], + daysWorkMissedEnd: [''], + workersCompensationClaimNumber: [''], + employers: fb.array([]), + documents: fb.array([]) + }; - return fb.group(group); - } + return fb.group(group); + } - createEmployerInfo(fb: FormBuilder): FormGroup { - return fb.group({ - employerName: [''], - employerPhoneNumber: [''], - employerFax: [''], - employerEmail: ['', [Validators.email]], - employerFirstName: [''], - employerLastName: [''], - employerAddress: fb.group({ - line1: ['',], - line2: [''], - city: ['',], - postalCode: ['', [Validators.pattern(this.postalRegex)]], - province: [{ value: 'British Columbia', disabled: false }], - country: [{ value: 'Canada', disabled: false }], - }), - contactable: [''], - }); - } -} \ No newline at end of file + createEmployerInfo(fb: FormBuilder): FormGroup { + return fb.group({ + employerName: [''], + employerPhoneNumber: [''], + employerFax: [''], + employerEmail: ['', [Validators.email]], + employerFirstName: [''], + employerLastName: [''], + employerAddress: fb.group({ + line1: [''], + line2: [''], + city: [''], + postalCode: ['', [Validators.pattern(this.postalRegex)]], + province: [{ value: 'British Columbia', disabled: false }], + country: [{ value: 'Canada', disabled: false }] + }), + contactable: [''] + }); + } +} diff --git a/vsd-app/ClientApp/src/app/shared/enums-list.ts b/vsd-app/ClientApp/src/app/shared/enums-list.ts index 0992c6d2..594fcc8e 100644 --- a/vsd-app/ClientApp/src/app/shared/enums-list.ts +++ b/vsd-app/ClientApp/src/app/shared/enums-list.ts @@ -1,22 +1,21 @@ export const MY_FORMATS = { parse: { - dateInput: 'LL', + dateInput: 'LL' }, display: { dateInput: 'YYYY-MM-DD', monthYearLabel: 'MMM YYYY', dateA11yLabel: 'YYYY-MM-DD', - monthYearA11yLabel: 'MMMM YYYY', - }, + monthYearA11yLabel: 'MMMM YYYY' + } }; export class EnumHelper { - public Gender = { 0: '--', 100000000: 'M', 100000001: 'F', - 100000002: 'X', + 100000002: 'X' }; public RelationshipToVictim = { @@ -25,8 +24,8 @@ export class EnumHelper { 100000001: 'Parent/Guardian', 100000002: 'Child', 100000003: 'Sibling', - 100000004: 'Other', - } + 100000004: 'Other' + }; public MaritalStatus = { 0: '--', @@ -35,180 +34,181 @@ export class EnumHelper { 100000002: 'Widowed', 100000003: 'Divorced', 100000004: 'Separated', - 100000005: 'Single', - } + 100000005: 'Single' + }; public VoicemailOptions = { - 0: "", - 100000000: "Primary and Alternate", - 100000001: "Primary only", - 100000002: "Alternate only", - 100000003: "No Voicemail", - } + 0: '', + 100000000: 'Primary and Alternate', + 100000001: 'Primary only', + 100000002: 'Alternate only', + 100000003: 'No Voicemail' + }; public ApplicantPreferredMethodOfContact = { 0: '--', 2: 'Phone Call', 1: 'Email', 4: 'Primary Mail', - 100000002: 'Alternate Mail', - } + 100000002: 'Alternate Mail' + }; public ParticipantPreferredMethodOfContact = { // There are two drop downs being accessed by this which is why items appear twice 0: '--', 100000000: 'Email', 100000001: 'Phone Call', - 100000002: 'Mail', - } + 100000002: 'Mail' + }; public ReportMadeToPolice = { 0: '--', 100000000: 'Yes', 100000001: 'No', - 100000002: 'Unknown', - } + 100000002: 'Unknown' + }; public OffenderBeenCharged = { 0: '--', 100000000: 'Yes', 100000001: 'No', - 100000002: 'Unknown', - } + 100000002: 'Unknown' + }; public HaveYouSuedOffender = { 0: '--', 100000000: 'No', - 100000001: 'Yes', - } + 100000001: 'Yes' + }; public IntendToSueOffender = { 0: '--', 100000000: 'Yes', 100000001: 'No', - 100000002: 'Undecided', - } + 100000002: 'Undecided' + }; public ApplyToCourtForMoneyFromOffender = { 0: '--', 100000000: 'Yes', 100000001: 'No', - 100000002: 'Not Applicable (No trial/conviction)', - } + 100000002: 'Not Applicable (No trial/conviction)' + }; public WillBeTakingLegalAction = { 0: '--', 100000000: 'Yes', 100000001: 'No', - 100000002: 'Unsure', - } + 100000002: 'Unsure' + }; public WereYouEmployedAtTimeOfCrime = { 0: '--', 100000000: 'No', - 100000001: 'Yes', - } + 100000001: 'Yes' + }; public AllowCvapStaffSharing = { 0: '--', 100000000: 'No', 100000001: 'Yes-Person', - 100000002: 'Yes-Agency', - } + 100000002: 'Yes-Agency' + }; public AllowCvapStaffSharingValues = { - 'No': 100000000, - 'Yes_Person': 100000001, - 'Yes_Agency': 100000002, - } + No: 100000000, + Yes_Person: 100000001, + Yes_Agency: 100000002 + }; public boolEnum = { 0: '--', 100000000: 'No', - 100000001: 'Yes', - } + 100000001: 'Yes' + }; public boolValues = { No: 100000000, Yes: 100000001 - } + }; public CompletingOnBehalfOf = { 0: '--', 100000000: 'Completing this application for myself', 100000001: 'A Victim Service Worker or other person helping a victim complete this application', 100000002: 'A parent completing this application for my minor child (under 19 years of age)', - 100000003: 'A legal representative or legal guardian completing this application on behalf of someone else, or a third party completing on behalf of an incapable adult.', - } + 100000003: + 'A legal representative or legal guardian completing this application on behalf of someone else, or a third party completing on behalf of an incapable adult.' + }; public ProviderSpecialistType = { 0: '--', 100000001: 'Specialist', 100000002: 'Counsellor / Psychologist', 100000003: 'Dentist', - 100000004: 'Other', - } + 100000004: 'Other' + }; public InvoiceCounsellingType = { 0: '--', 100000000: 'Counselling Session', 100000001: 'Court Supporting Counselling', - 100000002: 'Psycho-educational sessions', - } + 100000002: 'Psycho-educational sessions' + }; public CRMGender = { - Male: { val: 100000000, name: "M" }, - Female: { val: 100000001, name: "F" }, - X: { val: 100000002, name: "X" }, - } + Male: { val: 100000000, name: 'M' }, + Female: { val: 100000001, name: 'F' }, + X: { val: 100000002, name: 'X' } + }; public ContactMethods = { - BLANK: { val: 0, name: "--" }, - Phone: { val: 2, name: "Phone Call" }, - Email: { val: 1, name: "Email" }, - Mail: { val: 4, name: "Mail" }, - } + BLANK: { val: 0, name: '--' }, + Phone: { val: 2, name: 'Phone Call' }, + Email: { val: 1, name: 'Email' }, + Mail: { val: 4, name: 'Mail' } + }; public ParticipantContactMethods = { - Email: { val: 100000000, name: "Email" }, - Phone: { val: 100000001, name: "Phone Call" }, - Mail: { val: 100000002, name: "Mail" }, - } + Email: { val: 100000000, name: 'Email' }, + Phone: { val: 100000001, name: 'Phone Call' }, + Mail: { val: 100000002, name: 'Mail' } + }; public ParticipantRestitutionContactMethods = { - BLANK: { val: 0, name: "--" }, - Email: { val: 100000000, name: "Email" }, - Mail: { val: 100000001, name: "Mail" }, - Phone: { val: 100000002, name: "Phone Call" }, - SMS: { val: 100000003, name: "SMS" }, - } + BLANK: { val: 0, name: '--' }, + Email: { val: 100000000, name: 'Email' }, + Mail: { val: 100000001, name: 'Mail' }, + Phone: { val: 100000002, name: 'Phone Call' }, + SMS: { val: 100000003, name: 'SMS' } + }; public IndigenousStatus = { - BLANK: { val: 0, name: "--" }, - First_Nations: { val: 100000000, name: "First Nations" }, - Metis: { val: 100000001, name: "Métis" }, - Inuit: { val: 100000002, name: "Inuit" }, - Prefere_Not_To_Answer: { val: 100000003, name: "Prefer Not to Answer" }, - Not_Applicable: { val: 100000004, name: "Not Applicable" }, - } + BLANK: { val: 0, name: '--' }, + First_Nations: { val: 100000000, name: 'First Nations' }, + Metis: { val: 100000001, name: 'Métis' }, + Inuit: { val: 100000002, name: 'Inuit' }, + Prefere_Not_To_Answer: { val: 100000003, name: 'Prefer Not to Answer' }, + Not_Applicable: { val: 100000004, name: 'Not Applicable' } + }; public LeaveVoicemail = { - BLANK: { val: null, name: "--" }, - Primary_And_Alternate: { val: 100000000, name: "Primary and Alternate" }, - Primary_Only: { val: 100000001, name: "Primary only" }, - Altrernate_Only: { val: 100000002, name: "Alternate only" }, - No_Voicemail: { val: 100000003, name: "No Voicemail" }, - } + BLANK: { val: null, name: '--' }, + Primary_And_Alternate: { val: 100000000, name: 'Primary and Alternate' }, + Primary_Only: { val: 100000001, name: 'Primary only' }, + Altrernate_Only: { val: 100000002, name: 'Alternate only' }, + No_Voicemail: { val: 100000003, name: 'No Voicemail' } + }; } export const ResitutionForm = { - Victim: { val: 100000002, name: "Victim" }, - Offender: { val: 100000003, name: "Offender" }, + Victim: { val: 100000002, name: 'Victim' }, + Offender: { val: 100000003, name: 'Offender' } }; export enum CRMBoolean { True = 100000001, - False = 100000000, + False = 100000000 } export enum CRMMultiBoolean { True = 100000000, @@ -220,7 +220,7 @@ export enum ApplicationType { Victim_Application = 100000002, IFM_Application = 100000001, Witness_Application = 100000000, - Offender_Application = 100000003, + Offender_Application = 100000003 } export enum OnBehalfOf { diff --git a/vsd-app/ClientApp/src/app/shared/expense-information/expense-information.component.ts b/vsd-app/ClientApp/src/app/shared/expense-information/expense-information.component.ts index 4669c405..32596a74 100644 --- a/vsd-app/ClientApp/src/app/shared/expense-information/expense-information.component.ts +++ b/vsd-app/ClientApp/src/app/shared/expense-information/expense-information.component.ts @@ -1,14 +1,14 @@ -import { FormBase } from "../form-base"; -import { OnInit, Component, Input, OnDestroy } from "@angular/core"; -import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS, MatDialog, MatDatepickerInputEvent } from "@angular/material"; -import { FormGroup, ControlContainer, FormControl, AbstractControl, Validators, FormArray } from "@angular/forms"; -import { MomentDateAdapter } from "@angular/material-moment-adapter"; -import { MY_FORMATS, ApplicationType, CRMBoolean } from "../enums-list"; -import { SummaryOfBenefitsDialog } from "../../summary-of-benefits/summary-of-benefits.component"; +import { FormBase } from '../form-base'; +import { OnInit, Component, Input, OnDestroy } from '@angular/core'; +import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS, MatDialog, MatDatepickerInputEvent } from '@angular/material'; +import { FormGroup, ControlContainer, FormControl, AbstractControl, Validators, FormArray } from '@angular/forms'; +import { MomentDateAdapter } from '@angular/material-moment-adapter'; +import { MY_FORMATS, ApplicationType, CRMBoolean } from '../enums-list'; +import { SummaryOfBenefitsDialog } from '../../summary-of-benefits/summary-of-benefits.component'; import * as moment from 'moment'; -import { Subscription } from "rxjs"; -import { AddressHelper } from "../address/address.helper"; -import { iLookupData } from "../../interfaces/lookup-data.interface"; +import { Subscription } from 'rxjs'; +import { AddressHelper } from '../address/address.helper'; +import { iLookupData } from '../../interfaces/lookup-data.interface'; @Component({ selector: 'app-expense-information', @@ -19,8 +19,8 @@ import { iLookupData } from "../../interfaces/lookup-data.interface"; // application's root module. We provide it at the component level here, due to limitations of // our example generation script. { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, - { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }, - ], + { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS } + ] }) export class ExpenseInformationComponent extends FormBase implements OnInit, OnDestroy { @Input() formType: number; @@ -44,21 +44,20 @@ export class ExpenseInformationComponent extends FormBase implements OnInit, OnD loseWagesSubscription: Subscription; missedWorkDueToDeathOfVictimSubscription: Subscription; - constructor( - private controlContainer: ControlContainer, - private matDialog: MatDialog, - ) { + constructor(private controlContainer: ControlContainer, private matDialog: MatDialog) { super(); } ngOnInit() { this.form = this.controlContainer.control; - setTimeout(() => { this.form.markAsTouched(); }, 0); + setTimeout(() => { + this.form.markAsTouched(); + }, 0); // console.log("expense info component"); // console.log(this.form); if (this.formType === ApplicationType.Victim_Application) { - this.header = "Loss"; + this.header = 'Loss'; this.BENEFITS = [ 'haveMedicalExpenses', 'haveDentalExpenses', @@ -86,7 +85,6 @@ export class ExpenseInformationComponent extends FormBase implements OnInit, OnD ]; } if (this.formType === ApplicationType.IFM_Application) { - setTimeout(() => { let didMissWorkControl = this.form.get('missedWorkDueToDeathOfVictim'); let mayContactEmployer = this.form.get('mayContactEmployer').value === CRMBoolean.True; @@ -94,8 +92,7 @@ export class ExpenseInformationComponent extends FormBase implements OnInit, OnD if (this.form.parent.get('crimeInformation.victimDeceasedFromCrime').value == CRMBoolean.True) { didMissWorkControl.setValidators([Validators.required]); this.mayContactEmployerChange(mayContactEmployer); - } - else { + } else { didMissWorkControl.clearValidators(); didMissWorkControl.setErrors(null); this.mayContactEmployerChange(false); @@ -115,8 +112,7 @@ export class ExpenseInformationComponent extends FormBase implements OnInit, OnD if (value === CRMBoolean.True) { didYouLoseWagesControl.setValidators([Validators.required]); // minimumOtherBenefitsSelected.setValidators([Validators.required]); - } - else { + } else { didYouLoseWagesControl.clearValidators(); didYouLoseWagesControl.setErrors(null); didYouLoseWagesControl.patchValue(''); @@ -146,8 +142,7 @@ export class ExpenseInformationComponent extends FormBase implements OnInit, OnD // let employersEmployerPhoneNumber = employerGroup.controls['employerPhoneNumber'] as FormControl; // this.setControlValidators(employersEmployerPhoneNumber, [Validators.required]); } - } - else { + } else { daysMissedStartControl.patchValue(''); this.clearControlValidators(daysMissedStartControl); daysMissedEndControl.patchValue(''); @@ -181,10 +176,9 @@ export class ExpenseInformationComponent extends FormBase implements OnInit, OnD daysMissedStartControl.updateValueAndValidity(); daysMissedEndControl.updateValueAndValidity(); }); - }, 0); - this.header = "Benefits"; + this.header = 'Benefits'; this.BENEFITS = [ 'haveCounsellingExpenses', 'haveCounsellingTransportation', @@ -208,11 +202,11 @@ export class ExpenseInformationComponent extends FormBase implements OnInit, OnD 'haveCanadaPensionPlanBenefits', 'haveAboriginalAffairsAndNorthernDevelopmentCanadaBenefits', 'haveCivilActionBenefits', - 'haveOtherBenefits', + 'haveOtherBenefits' ]; } if (this.formType === ApplicationType.Witness_Application) { - this.header = "Benefits"; + this.header = 'Benefits'; this.BENEFITS = [ 'haveCounsellingExpenses', 'haveCounsellingTransportation', @@ -244,7 +238,7 @@ export class ExpenseInformationComponent extends FormBase implements OnInit, OnD daysWorkMissedEndChange() { let endDate = moment(this.form.get('daysWorkMissedEnd').value); - this.showCurrentlyOffWork = endDate.isSame(new Date(), "day"); + this.showCurrentlyOffWork = endDate.isSame(new Date(), 'day'); } changeGroupValidity(values: any): void { @@ -258,13 +252,11 @@ export class ExpenseInformationComponent extends FormBase implements OnInit, OnD //determine if one of the checkboxes is true let oneChecked = false; - x.forEach(c => { + x.forEach((c) => { // TODO: This should always return if not null because truthy. Second if should never trigger? - if (oneChecked) - return; + if (oneChecked) return; if (c instanceof FormControl) { - if (c.value === true) - oneChecked = true; + if (c.value === true) oneChecked = true; } }); // fake a 'true' as a string @@ -285,13 +277,11 @@ export class ExpenseInformationComponent extends FormBase implements OnInit, OnD //determine if one of the checkboxes is true let oneChecked = false; - x.forEach(c => { + x.forEach((c) => { // TODO: This should always return if not null because truthy. Second if should never trigger? - if (oneChecked) - return; + if (oneChecked) return; if (c instanceof FormControl) { - if (c.value === true) - oneChecked = true; + if (c.value === true) oneChecked = true; } }); // fake a 'true' as a string @@ -312,8 +302,7 @@ export class ExpenseInformationComponent extends FormBase implements OnInit, OnD this.setControlValidators(nameControl, [Validators.required]); this.setControlValidators(phoneControl, [Validators.required]); this.addressHelper.setAddressAsRequired(thisEmployer, 'employerAddress'); - } - else { + } else { this.clearControlValidators(nameControl); this.clearControlValidators(phoneControl); this.addressHelper.clearAddressValidatorsAndErrors(thisEmployer, 'employerAddress'); @@ -344,16 +333,21 @@ export class ExpenseInformationComponent extends FormBase implements OnInit, OnD setEmployerPhoneValidators(employer: AbstractControl) { let phoneMinLength = 10; let phoneMaxLength = 15; - if (employer.get('employerAddress.country').value === 'Canada' || employer.get('employerAddress.country').value === 'United States of America') { + if ( + employer.get('employerAddress.country').value === 'Canada' || + employer.get('employerAddress.country').value === 'United States of America' + ) { phoneMinLength = 10; - } - else { + } else { phoneMinLength = 8; } let phoneControl = employer.get('employerPhoneNumber'); let faxControl = employer.get('employerFax'); - this.setControlValidators(phoneControl, [Validators.minLength(phoneMinLength), Validators.maxLength(phoneMaxLength)]); + this.setControlValidators(phoneControl, [ + Validators.minLength(phoneMinLength), + Validators.maxLength(phoneMaxLength) + ]); this.setControlValidators(faxControl, [Validators.minLength(phoneMinLength), Validators.maxLength(phoneMaxLength)]); phoneControl.patchValue(phoneControl.value); faxControl.patchValue(faxControl.value); diff --git a/vsd-app/ClientApp/src/app/shared/expense-information/expense-information.helper.ts b/vsd-app/ClientApp/src/app/shared/expense-information/expense-information.helper.ts index 784f4cb9..92cf2485 100644 --- a/vsd-app/ClientApp/src/app/shared/expense-information/expense-information.helper.ts +++ b/vsd-app/ClientApp/src/app/shared/expense-information/expense-information.helper.ts @@ -1,6 +1,6 @@ -import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms"; -import { ApplicationType } from "../enums-list"; -import { POSTAL_CODE } from "../regex.constants"; +import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms'; +import { ApplicationType } from '../enums-list'; +import { POSTAL_CODE } from '../regex.constants'; export class ExpenseInfoHelper { postalRegex = POSTAL_CODE; @@ -22,7 +22,7 @@ export class ExpenseInfoHelper { otherSpecificExpenses: [''], additionalBenefitsDetails: [''], minimumExpensesSelected: ['', Validators.required], - minimumOtherBenefitsSelected: [''],//, Validators.required], + minimumOtherBenefitsSelected: [''], //, Validators.required], haveDisabilityPlanBenefits: [false], haveEmploymentInsuranceBenefits: [false], @@ -32,7 +32,7 @@ export class ExpenseInfoHelper { haveCivilActionBenefits: [false], haveOtherBenefits: [false], otherSpecificBenefits: [''], - noneOfTheAboveBenefits: [false], + noneOfTheAboveBenefits: [false] }; if (form_type === ApplicationType.Witness_Application) { @@ -44,7 +44,7 @@ export class ExpenseInfoHelper { minimumOtherBenefitsSelected: [''], // Dynamically required haveCrimeSceneCleaningExpenses: [false], - additionalBenefitsDetails: [''],//, Validators.required], ?? + additionalBenefitsDetails: [''] //, Validators.required], ?? }; } if (form_type === ApplicationType.IFM_Application) { @@ -66,7 +66,7 @@ export class ExpenseInfoHelper { haveOtherBenefits: [false], otherSpecificBenefits: [''], - missedWorkDueToDeathOfVictim: [''],//, Validators.required], + missedWorkDueToDeathOfVictim: [''], //, Validators.required], didYouLoseWages: [''], //, Validators.required], sin: ['', [Validators.minLength(9), Validators.maxLength(9)]], daysWorkMissedStart: [''], //, Validators.required], @@ -74,19 +74,19 @@ export class ExpenseInfoHelper { employers: fb.array([this.createEmployerItem(fb)]), mayContactEmployer: [''], minimumExpensesSelected: ['', Validators.required], - minimumOtherBenefitsSelected: [''],//, Validators.required], + minimumOtherBenefitsSelected: [''], //, Validators.required], - additionalBenefitsDetails: [''],//, Validators.required], ?? + additionalBenefitsDetails: [''], //, Validators.required], ?? haveLifeInsuranceBenefits: [false], haveDisabilityPlanBenefits: [false], haveEmploymentInsuranceBenefits: [false], haveIncomeAssistanceBenefits: [false], haveCanadaPensionPlanBenefits: [false], haveAboriginalAffairsAndNorthernDevelopmentCanadaBenefits: [false], - haveCivilActionBenefits: [false], + haveCivilActionBenefits: [false] // Have to turn validation off for now - in case no death date. Though, if death date, then there should be validation // TODO: Figure out how to do this. - } + }; } return fb.group(group); } @@ -105,7 +105,7 @@ export class ExpenseInfoHelper { city: [''], postalCode: ['', [Validators.pattern(this.postalRegex)]], province: [{ value: 'British Columbia', disabled: false }], - country: [{ value: 'Canada', disabled: false }], + country: [{ value: 'Canada', disabled: false }] }) }); } diff --git a/vsd-app/ClientApp/src/app/shared/field/field.component.scss b/vsd-app/ClientApp/src/app/shared/field/field.component.scss index 97852a20..5a7b736a 100644 --- a/vsd-app/ClientApp/src/app/shared/field/field.component.scss +++ b/vsd-app/ClientApp/src/app/shared/field/field.component.scss @@ -1,16 +1,16 @@ .error-states { - color: #d8292f + color: #d8292f; } .error-container { - margin-top: 5px; + margin-top: 5px; } .app-field { - margin-bottom: 15px; + margin-bottom: 15px; } .red-asterisk { - position: absolute; - margin-left: 3px; -} \ No newline at end of file + position: absolute; + margin-left: 3px; +} diff --git a/vsd-app/ClientApp/src/app/shared/field/field.component.spec.ts b/vsd-app/ClientApp/src/app/shared/field/field.component.spec.ts index 047abcd7..59b14fdc 100644 --- a/vsd-app/ClientApp/src/app/shared/field/field.component.spec.ts +++ b/vsd-app/ClientApp/src/app/shared/field/field.component.spec.ts @@ -8,9 +8,8 @@ describe('FieldComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - declarations: [ FieldComponent ] - }) - .compileComponents(); + declarations: [FieldComponent] + }).compileComponents(); })); beforeEach(() => { diff --git a/vsd-app/ClientApp/src/app/shared/field/field.component.ts b/vsd-app/ClientApp/src/app/shared/field/field.component.ts index f156b285..1ea6feb3 100644 --- a/vsd-app/ClientApp/src/app/shared/field/field.component.ts +++ b/vsd-app/ClientApp/src/app/shared/field/field.component.ts @@ -15,9 +15,7 @@ export class FieldComponent implements OnInit { @Input() errorMessage: string; @Input() disabled: boolean; - constructor() { } - - ngOnInit() { - } + constructor() {} + ngOnInit() {} } diff --git a/vsd-app/ClientApp/src/app/shared/file-uploader/file-uploader.component.scss b/vsd-app/ClientApp/src/app/shared/file-uploader/file-uploader.component.scss index ef68d839..09d94119 100644 --- a/vsd-app/ClientApp/src/app/shared/file-uploader/file-uploader.component.scss +++ b/vsd-app/ClientApp/src/app/shared/file-uploader/file-uploader.component.scss @@ -1,46 +1,46 @@ ::ng-deep .drop-zone { - border: 1px dashed #a5badb !important; - background-color: #f1f4fa; - border-radius: 5px !important; - padding-bottom: 20px; + border: 1px dashed #a5badb !important; + background-color: #f1f4fa; + border-radius: 5px !important; + padding-bottom: 20px; } ::ng-deep .content { - color: #424242 !important; + color: #424242 !important; } .file-list { - background-color: #f1f4fa; - margin-bottom: 3px; - display: flex; - justify-content: space-between; - padding: 3px 7px; - margin-right: 10px; + background-color: #f1f4fa; + margin-bottom: 3px; + display: flex; + justify-content: space-between; + padding: 3px 7px; + margin-right: 10px; } .no-drop { - cursor: no-drop; + cursor: no-drop; } .upload-wrapper { - position: relative; - margin: auto; + position: relative; + margin: auto; } .remove-chip { - margin-top: 16px !important; - margin-left: 10px !important; + margin-top: 16px !important; + margin-left: 10px !important; } .remove-icon { - margin-left: 5px; - position: relative; - top: -1px; - opacity: 0.5; - font-size: 17px; + margin-left: 5px; + position: relative; + top: -1px; + opacity: 0.5; + font-size: 17px; } .accepted-file-types { - color: gray; - font-size: 15px; + color: gray; + font-size: 15px; } diff --git a/vsd-app/ClientApp/src/app/shared/file-uploader/file-uploader.component.spec.ts b/vsd-app/ClientApp/src/app/shared/file-uploader/file-uploader.component.spec.ts index fc21b866..2c1c2db1 100644 --- a/vsd-app/ClientApp/src/app/shared/file-uploader/file-uploader.component.spec.ts +++ b/vsd-app/ClientApp/src/app/shared/file-uploader/file-uploader.component.spec.ts @@ -8,9 +8,8 @@ describe('FileUploaderComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - declarations: [ FileUploaderComponent ] - }) - .compileComponents(); + declarations: [FileUploaderComponent] + }).compileComponents(); })); beforeEach(() => { diff --git a/vsd-app/ClientApp/src/app/shared/file-uploader/file-uploader.component.ts b/vsd-app/ClientApp/src/app/shared/file-uploader/file-uploader.component.ts index f2534ba6..2405cc3c 100644 --- a/vsd-app/ClientApp/src/app/shared/file-uploader/file-uploader.component.ts +++ b/vsd-app/ClientApp/src/app/shared/file-uploader/file-uploader.component.ts @@ -17,31 +17,32 @@ export class FileUploaderComponent implements OnInit { MAX_FILE_SIZE = 2 * 1024 * 1024; //2MB MAX_TOTAL_FILE_SIZE = 3.5 * 1024 * 1024; //3.5MB - constructor(private fb: FormBuilder, - private controlContainer: ControlContainer, - public snackBar: MatSnackBar) { } + constructor(private fb: FormBuilder, private controlContainer: ControlContainer, public snackBar: MatSnackBar) {} ngOnInit() { this.form = this.controlContainer.control; } fakeBrowseClick(): void { - this.myInputVariable.nativeElement.value = ""; + this.myInputVariable.nativeElement.value = ''; // the UI element for the native element style doesn't match so we hide it and fake the user click. this.myInputVariable.nativeElement.click(); } onFilesAdded(files: FileList): void { - let totalSize = this.form.parent.get("totalAttachmentSize").value; + let totalSize = this.form.parent.get('totalAttachmentSize').value; for (let i = 0; i < files.length; i++) { if (files[i].size > this.MAX_FILE_SIZE) { // console.log("File too big:", (files[i].size / (1024 * 1024)).toFixed(2) + "MB"); this.snackBar.open('File cannot exceed 2MB', 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); continue; } - if ((totalSize + files[i].size) > this.MAX_TOTAL_FILE_SIZE) { + if (totalSize + files[i].size > this.MAX_TOTAL_FILE_SIZE) { // console.log("Total size too big:", ((totalSize + files[i].size) / (1024 * 1024)).toFixed(2) + "MB") - this.snackBar.open('Files uploaded to application cannot exceed 3.5MB', 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); + this.snackBar.open('Files uploaded to application cannot exceed 3.5MB', 'Fail', { + duration: 3500, + panelClass: ['red-snackbar'] + }); continue; } @@ -59,29 +60,30 @@ export class FileUploaderComponent implements OnInit { reader.onload = () => { let body = reader.result.toString(); body = body.split(',').slice(-1)[0]; - let fileIndex = this.documents.controls.findIndex(doc => doc.get('filename').value === files.item(i).name); + let fileIndex = this.documents.controls.findIndex((doc) => doc.get('filename').value === files.item(i).name); if (fileIndex >= 0) { this.documents.controls[fileIndex].get('body').patchValue(body); - } - else { - this.documents.push(this.fb.group({ - filename: [files.item(i).name], - body: [body], - subject: [''], - size: files[i].size, - })); + } else { + this.documents.push( + this.fb.group({ + filename: [files.item(i).name], + body: [body], + subject: [''], + size: files[i].size + }) + ); } }; - reader.onerror = error => console.log('Error: ', error); + reader.onerror = (error) => console.log('Error: ', error); } - this.form.parent.get("totalAttachmentSize").patchValue(totalSize); + this.form.parent.get('totalAttachmentSize').patchValue(totalSize); } removeItem(index: number): void { - let totalSize = this.form.parent.get("totalAttachmentSize").value; - let fileSize = this.documents.at(index).get("size").value; + let totalSize = this.form.parent.get('totalAttachmentSize').value; + let fileSize = this.documents.at(index).get('size').value; totalSize -= fileSize; - this.form.parent.get("totalAttachmentSize").patchValue(totalSize); + this.form.parent.get('totalAttachmentSize').patchValue(totalSize); this.documents.removeAt(index); } -} \ No newline at end of file +} diff --git a/vsd-app/ClientApp/src/app/shared/form-base.ts b/vsd-app/ClientApp/src/app/shared/form-base.ts index 34a08b19..1ce517c3 100644 --- a/vsd-app/ClientApp/src/app/shared/form-base.ts +++ b/vsd-app/ClientApp/src/app/shared/form-base.ts @@ -16,8 +16,7 @@ export class FormBase { isFieldValid(field: string, disabled: boolean = false) { if (disabled === true) return true; let formField = this.form.get(field); - if (!formField || formField.value === null) - return true; + if (!formField || formField.value === null) return true; if (field === 'personalInformation.sin' || field === 'victimInformation.sin' || field === 'sin') { let validator = formField.validator({} as AbstractControl); let isRequired = validator && validator.required ? true : false; @@ -50,33 +49,43 @@ export class FormBase { even = sin // take the digits at the even indices - .filter(function (_, i) { return i % 2; }) + .filter(function (_, i) { + return i % 2; + }) // multiply them by two - .map(function (n) { return n * 2; }) + .map(function (n) { + return n * 2; + }) // and split them into individual digits - .join('').split(''); + .join('') + .split(''); tot = sin // take the digits at the odd indices - .filter(function (_, i) { return !(i % 2); }) + .filter(function (_, i) { + return !(i % 2); + }) // concatenate them with the transformed numbers above .concat(even) // it's currently an array of strings; we want numbers - .map(function (n) { return +n; }) + .map(function (n) { + return +n; + }) // and take the sum - .reduce(function (acc, cur) { return acc + cur; }); + .reduce(function (acc, cur) { + return acc + cur; + }); // compare the result against the check digit return check === (10 - (tot % 10)) % 10; - } else return false;// throw sin + ' is not a valid sin number.'; + } else return false; // throw sin + ' is not a valid sin number.'; } isArrayFieldValid(formArrayName: string, arrayControl: string, arrayIndex: number) { let formArray = this.form.get(formArrayName); let indexedControl = formArray.controls[arrayIndex]; let formField = indexedControl.get(arrayControl); - if (formField == null) - return true; + if (formField == null) return true; return formField.valid || !formField.touched; } @@ -86,8 +95,25 @@ export class FormBase { } public rejectIfNotDigitOrBackSpace(event) { - const acceptedKeys = ['Backspace', 'Tab', 'End', 'Home', 'ArrowLeft', 'ArrowRight', 'Control', - '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']; + const acceptedKeys = [ + 'Backspace', + 'Tab', + 'End', + 'Home', + 'ArrowLeft', + 'ArrowRight', + 'Control', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + '0' + ]; if (acceptedKeys.indexOf(event.key) === -1) { event.preventDefault(); } @@ -98,7 +124,7 @@ export class FormBase { if (control.value === true) { return null; } else { - return { 'shouldBeTrue': 'But value is false' }; + return { shouldBeTrue: 'But value is false' }; } }; } @@ -121,7 +147,7 @@ export class FormBase { const name = control.get('haveMedicalExpenses'); const alterEgo = control.get('haveDentalExpenses'); - return name.value != false && alterEgo.value != false ? { 'identityRevealed': true } : null; + return name.value != false && alterEgo.value != false ? { identityRevealed: true } : null; }; public requiredCheckboxGroupValidator(checkboxFields: string[]): ValidatorFn { @@ -130,7 +156,7 @@ export class FormBase { return null; } let valid = false; - checkboxFields.forEach(f => { + checkboxFields.forEach((f) => { valid = valid || control.parent.get(f).value; }); return valid ? null : { 'required-set': { value: control.value } }; @@ -146,15 +172,15 @@ export class FormBase { if (!parentIsChecked) { return null; } - return control.value ? null : { 'required': { value: control.value } }; + return control.value ? null : { required: { value: control.value } }; }; } validateAllFormFields(formGroup: any) { - Object.keys(formGroup.controls).forEach(field => { + Object.keys(formGroup.controls).forEach((field) => { const control = formGroup.get(field); if (control.valid === false) { - console.log("invalid: ", field); + console.log('invalid: ', field); } if (control instanceof FormControl) { @@ -177,7 +203,7 @@ export class FormBase { } getErrors(formGroup: any, errors: any = {}) { - Object.keys(formGroup.controls).forEach(field => { + Object.keys(formGroup.controls).forEach((field) => { const control = formGroup.get(field); if (control instanceof FormControl) { errors[field] = control.errors; @@ -191,19 +217,16 @@ export class FormBase { } orEmpty(amI: FormControl): string { - if (amI == null || amI === undefined) - return "--"; + if (amI == null || amI === undefined) return '--'; - if (amI.value.length == 0) - return "--"; + if (amI.value.length == 0) return '--'; return amI.value; } isChildFieldValid(parent: string, field: string) { let formField = this.form.get(parent); - if (formField == null) - return true; + if (formField == null) return true; return formField.get(field).valid || !formField.get(field).touched; } @@ -214,9 +237,11 @@ export class FormBase { formGroup.controls[item].setErrors(null); // Checks for empty string and empty array. - let hasValue = (formGroup.controls[item].value instanceof Array) ? formGroup.controls[item].value.length > 0 : - !(formGroup.controls[item].value === ""); - return (hasValue) ? false : true; + let hasValue = + formGroup.controls[item].value instanceof Array + ? formGroup.controls[item].value.length > 0 + : !(formGroup.controls[item].value === ''); + return hasValue ? false : true; }); } @@ -224,35 +249,34 @@ export class FormBase { return (control: FormControl): { [key: string]: any } => { let formGroup = control.root; if (formGroup instanceof FormGroup) { - // Only check if all FormControls are siblings(& present on the nearest FormGroup) - if (controlKeys.every((item) => { - return formGroup.get(item) != null; - })) { + if ( + controlKeys.every((item) => { + return formGroup.get(item) != null; + }) + ) { let result = this.controlsHaveValueCheck(controlKeys, formGroup); // If any item is valid return null, if all are invalid return required error. - return (result.some((item) => { + return result.some((item) => { return item === false; - })) ? null : { required: true }; + }) + ? null + : { required: true }; } } return null; - } + }; } - public hasValueSet(controlName: string): boolean { var control = this.form.get(controlName); - if (control == null || control === undefined) - return false; + if (control == null || control === undefined) return false; - if (control.value == null || control.value === undefined) - return false; + if (control.value == null || control.value === undefined) return false; - if (control.value.length == 0 || control.value.length === undefined) - return false; + if (control.value.length == 0 || control.value.length === undefined) return false; return control.value.length > 0; } @@ -263,16 +287,18 @@ export class FormBase { public requiredSelectChildValidator(selectField: string, conditionalValue: any[]): ValidatorFn { return (control: AbstractControl): { [key: string]: any } | null => { - if (!control.parent - || !control.parent.get(selectField) - || conditionalValue.indexOf(control.parent.get(selectField).value) === -1) { + if ( + !control.parent || + !control.parent.get(selectField) || + conditionalValue.indexOf(control.parent.get(selectField).value) === -1 + ) { return null; } const parentIsChecked = control.parent.get(selectField).value; if (!parentIsChecked) { return null; } - return control.value ? null : { 'required': { value: control.value } }; + return control.value ? null : { required: { value: control.value } }; }; } @@ -280,45 +306,37 @@ export class FormBase { public checkmarkOrEmpty(controlName: string): string { var control = this.form.get(controlName); - if (control.value === true) - return ' '; + if (control.value === true) return ' '; return '--'; } public checkmarkFromControl(control: AbstractControl): string { - if (control.value === true) - return ' '; + if (control.value === true) return ' '; return '--'; } public valueOrEmpty(controlName: any, emptyValue = '--'): string { let control = null; - if (typeof (controlName) == 'string') - control = this.form.get(controlName); + if (typeof controlName == 'string') control = this.form.get(controlName); - if (controlName instanceof FormGroup) - control = controlName; + if (controlName instanceof FormGroup) control = controlName; - if (controlName instanceof FormControl) - control = controlName; + if (controlName instanceof FormControl) control = controlName; - if (control == null || control === undefined) - return emptyValue; + if (control == null || control === undefined) return emptyValue; - if (control.value == null || control.value === undefined) - return emptyValue; + if (control.value == null || control.value === undefined) return emptyValue; var value = control.value; - if (typeof (value) == 'string' && value.length == 0) - return emptyValue; + if (typeof value == 'string' && value.length == 0) return emptyValue; - if (typeof (value) == 'number' && value == 0) { + if (typeof value == 'number' && value == 0) { return emptyValue; } - if (typeof (value) == 'boolean') { + if (typeof value == 'boolean') { return value ? 'Yes' : 'No'; } @@ -328,29 +346,24 @@ export class FormBase { public valueForEnum(controlName: any): number { let control = null; - if (typeof (controlName) == 'string') - control = this.form.get(controlName); + if (typeof controlName == 'string') control = this.form.get(controlName); - if (controlName instanceof FormGroup) - control = controlName; + if (controlName instanceof FormGroup) control = controlName; - if (controlName instanceof FormControl) - control = controlName; + if (controlName instanceof FormControl) control = controlName; - if (control == null || control === undefined || control.value == null || control.value === undefined) - return 0; + if (control == null || control === undefined || control.value == null || control.value === undefined) return 0; var value = control.value; - if (typeof (value) == 'string') { + if (typeof value == 'string') { if (!isNaN(parseFloat(value)) && isFinite(+value)) { return parseInt(value); - } - else { - return 0 + } else { + return 0; } } - if (typeof (value) !== 'number') { + if (typeof value !== 'number') { return 0; } @@ -363,8 +376,7 @@ export class FormBase { for (var i = 0; i < values.length; i++) { var control = this.valueOrEmpty(values[i]); - if (control !== "--") - output.push(control); + if (control !== '--') output.push(control); } return output.join(' '); @@ -375,14 +387,13 @@ export class FormBase { for (var i = 0; i < values.length; i++) { var control = this.valueOrEmpty(values[i]); - if (control !== "--") { + if (control !== '--') { let formattedDate = _moment(control).format('MMM Do, Y'); output.push(formattedDate); } } - if (output.length == 0) - return '--'; + if (output.length == 0) return '--'; return output.join(' - '); } @@ -392,8 +403,7 @@ export class FormBase { var control2 = this.valueOrEmpty(sin1); var control3 = this.valueOrEmpty(sin1); - if (control1 == '--' || control2 == '--' || control3 == '--') - return '--'; + if (control1 == '--' || control2 == '--' || control3 == '--') return '--'; return control1 + '-' + control2 + '-' + control3; } @@ -401,11 +411,9 @@ export class FormBase { public displayMailingSubAddress(addressControl: any): string { let control = null; - if (typeof (addressControl) == 'string') - control = this.form.get(addressControl); + if (typeof addressControl == 'string') control = this.form.get(addressControl); - if (addressControl instanceof FormGroup) - control = addressControl; + if (addressControl instanceof FormGroup) control = addressControl; let line1 = control.value.line1 || ''; let line2 = control.value.line2 || ''; @@ -415,16 +423,11 @@ export class FormBase { let country = control.value.country || ''; let address = line1 + '
'; - if (line2 != '') - address += line2 + '
'; - if (city != '') - address += city + '
'; - if (province != '') - address += province + '
'; - if (country != '') - address += country + '
'; - if (postalCode != '') - address += postalCode; + if (line2 != '') address += line2 + '
'; + if (city != '') address += city + '
'; + if (province != '') address += province + '
'; + if (country != '') address += country + '
'; + if (postalCode != '') address += postalCode; return address; } @@ -432,14 +435,11 @@ export class FormBase { public displayMailingAddress(addressControl: any): string { let control = null; - if (typeof (addressControl) == 'string') - control = this.form.get(addressControl); + if (typeof addressControl == 'string') control = this.form.get(addressControl); - if (addressControl instanceof FormGroup) - control = addressControl; + if (addressControl instanceof FormGroup) control = addressControl; - if (control == null || control === undefined) - return "--"; + if (control == null || control === undefined) return '--'; let line1 = control.get('line1').value || ''; let line2 = control.get('line2').value || ''; @@ -449,23 +449,18 @@ export class FormBase { let country = control.get('country').value || ''; let address = line1 + '
'; - if (line2 != '') - address += line2 + '
'; - if (city != '') - address += city + '
'; - if (province != '') - address += province + '
'; - if (country != '') - address += country + '
'; - if (postalCode != '') - address += postalCode; + if (line2 != '') address += line2 + '
'; + if (city != '') address += city + '
'; + if (province != '') address += province + '
'; + if (country != '') address += country + '
'; + if (postalCode != '') address += postalCode; return address; } getOptionSetNameFromVal(optionSet, val: any) { - let ret = Object.values(optionSet).find((o) => o["val"] == val); - return ret ? ret["name"] : "--"; + let ret = Object.values(optionSet).find((o) => o['val'] == val); + return ret ? ret['name'] : '--'; } public trimValue(control: FormControl) { @@ -496,11 +491,11 @@ export class FormBase { gotoNextStep(stepper: MatStepper, emptyPage?: boolean): void { if (stepper) { const desiredFormIndex: number = stepper.selectedIndex; - const step_header = stepper._stepHeader.find(step => step.index == desiredFormIndex); - const step_label = step_header ? step_header.label : ""; - const this_step = stepper._steps.find(step => step.label == step_label); + const step_header = stepper._stepHeader.find((step) => step.index == desiredFormIndex); + const step_label = step_header ? step_header.label : ''; + const this_step = stepper._steps.find((step) => step.label == step_label); if (this_step) { - const formGroupName = this_step.stepControl.get("name").value; + const formGroupName = this_step.stepControl.get('name').value; // console.log(`Form for validation is ${formGroupName}.`); const formParts = this.form.get(formGroupName); // console.log(this.form); @@ -564,8 +559,7 @@ export class FormBase { target.get('alternatePhoneNumber').disable(options); target.get('email').disable(options); target.get('confirmEmail').disable(options); - } - else { + } else { target.get('phoneNumber').enable(options); target.get('alternatePhoneNumber').enable(options); target.get('email').enable(options); @@ -605,8 +599,7 @@ export class FormBase { target.get('postalCode').disable(options); target.get('province').disable(options); target.get('country').disable(options); - } - else { + } else { target.get('line1').enable(options); target.get('line2').enable(options); target.get('city').enable(options); @@ -650,8 +643,7 @@ export class FormBase { target.get('postalCode').disable(options); target.get('province').disable(options); target.get('country').disable(options); - } - else { + } else { target.get('line1').enable(); target.get('line2').enable(); target.get('city').enable(); @@ -689,8 +681,7 @@ export class FormBase { target.get('representativeAlternatePhoneNumber').disable(options); target.get('representativeEmail').disable(options); target.get('representativeConfirmEmail').disable(options); - } - else { + } else { target.get('representativePhoneNumber').enable(); target.get('representativeAlternatePhoneNumber').enable(); target.get('representativeEmail').enable(); @@ -703,7 +694,11 @@ export class FormBase { target.get('representativeConfirmEmail').updateValueAndValidity(options); } - setControlValidators(control: AbstractControl | FormControl, newValidator: ValidatorFn | ValidatorFn[], options = { onlySelf: false, emitEvent: true }) { + setControlValidators( + control: AbstractControl | FormControl, + newValidator: ValidatorFn | ValidatorFn[], + options = { onlySelf: false, emitEvent: true } + ) { control.setValidators(newValidator); control.updateValueAndValidity(options); } @@ -713,4 +708,4 @@ export class FormBase { control.clearValidators(); control.updateValueAndValidity(options); } -} \ No newline at end of file +} diff --git a/vsd-app/ClientApp/src/app/shared/hospital-list.ts b/vsd-app/ClientApp/src/app/shared/hospital-list.ts index 357653c6..32deb6b5 100644 --- a/vsd-app/ClientApp/src/app/shared/hospital-list.ts +++ b/vsd-app/ClientApp/src/app/shared/hospital-list.ts @@ -1,103 +1,103 @@ export const HOSPITALS = [ - "100 Mile District General Hospital", - "Abbotsford Regional Hospital and Cancer Centre", - "Aberdeen Hospital", - "Arrow Lakes Hospital", - "Ashcroft and District Hospital", + '100 Mile District General Hospital', + 'Abbotsford Regional Hospital and Cancer Centre', + 'Aberdeen Hospital', + 'Arrow Lakes Hospital', + 'Ashcroft and District Hospital', "B.C. Women's Hospital & Health Centre", - "BC Cancer Agency", - "Bella Coola General Hospital", - "Boundary Hospital", + 'BC Cancer Agency', + 'Bella Coola General Hospital', + 'Boundary Hospital', "British Columbia's Children's Hospital & Sunny Hill Health Centre for Children", - "Bulkley Valley District Hospital", - "Burnaby General Hospital", - "Campbell River & District General Hospital", - "Cariboo Memorial Hospital", - "Castlegar and District Community Health Centre", - "Chemainus Health Care Centre", - "Chetwynd General Hospital", - "Chilliwack General Hospital", - "Cormorant Island Community Health Centre", - "Cowichan District Hospital", - "Creston Valley Hospital", - "Dawson Creek and District Hospital", - "Delta Hospital", - "Dr. Helmcken Memorial Hospital", - "Eagle Park Health Care Facility", - "Eagle Ridge Hospital", - "East Kootenay Regional Hospital", - "Elk Valley Hospital", - "Fort Nelson General Hospital", - "Fort St. John General Hospital", - "Fraser Canyon Hospital", - "G.R. Baker Memorial Hospital", - "Glengarry Hospital", - "Golden and District General Hospital", - "Invermere and District Hospital", - "Kelowna General Hospital", - "Kitimat General Hospital", - "Kootenay Boundary Regional Hospital", - "Kootenay Lake Hospital", - "Lady Minto Gulf Islands Hospital", - "Ladysmith Community Health Centre", - "Lakes District Hospital and Health Centre", - "Langley Memorial Hospital", - "Lillooet District Hospital", - "Lions Gate Hospital", - "Mackenzie and District Hospital", - "McBride and District Hospital", - "Menno Hospital", - "Mills Memorial Hospital", - "Mission Memorial Hospital", - "Mount Saint Joseph Hospital", - "Mount St. Francis Hospital", - "Mt. Tolmie Hospital", - "Nanaimo Regional General Hospital", - "Nicola Valley Health Centre", - "Peace Arch Hospital", - "Penticton Regional Hospital", - "Port Alice Hospital", - "Port Hardy Hospital", - "Port McNeill and District Hospital", - "Powell River General Hospital", - "Prince Rupert Regional Hospital", - "Princeton General Hospital", - "Priory Hospital", - "Queen Charlotte Islands General Hospital", - "Queen Victoria Hospital", - "R.W. Large Memorial Hospital", - "Richmond Hospital", - "Ridge Meadows Hospital & Health Care Centre", - "Riverview Hospital", - "Royal Columbian Hospital", - "Royal Inland Hospital", - "Royal Jubilee Hospital", - "Saanich Peninsula Hospital", - "Shuswap Lake General Hospital", - "Slocan Community Health Centre", - "South Okanagan General Hospital", - "Sparwood Health Centre", - "Squamish General Hospital", + 'Bulkley Valley District Hospital', + 'Burnaby General Hospital', + 'Campbell River & District General Hospital', + 'Cariboo Memorial Hospital', + 'Castlegar and District Community Health Centre', + 'Chemainus Health Care Centre', + 'Chetwynd General Hospital', + 'Chilliwack General Hospital', + 'Cormorant Island Community Health Centre', + 'Cowichan District Hospital', + 'Creston Valley Hospital', + 'Dawson Creek and District Hospital', + 'Delta Hospital', + 'Dr. Helmcken Memorial Hospital', + 'Eagle Park Health Care Facility', + 'Eagle Ridge Hospital', + 'East Kootenay Regional Hospital', + 'Elk Valley Hospital', + 'Fort Nelson General Hospital', + 'Fort St. John General Hospital', + 'Fraser Canyon Hospital', + 'G.R. Baker Memorial Hospital', + 'Glengarry Hospital', + 'Golden and District General Hospital', + 'Invermere and District Hospital', + 'Kelowna General Hospital', + 'Kitimat General Hospital', + 'Kootenay Boundary Regional Hospital', + 'Kootenay Lake Hospital', + 'Lady Minto Gulf Islands Hospital', + 'Ladysmith Community Health Centre', + 'Lakes District Hospital and Health Centre', + 'Langley Memorial Hospital', + 'Lillooet District Hospital', + 'Lions Gate Hospital', + 'Mackenzie and District Hospital', + 'McBride and District Hospital', + 'Menno Hospital', + 'Mills Memorial Hospital', + 'Mission Memorial Hospital', + 'Mount Saint Joseph Hospital', + 'Mount St. Francis Hospital', + 'Mt. Tolmie Hospital', + 'Nanaimo Regional General Hospital', + 'Nicola Valley Health Centre', + 'Peace Arch Hospital', + 'Penticton Regional Hospital', + 'Port Alice Hospital', + 'Port Hardy Hospital', + 'Port McNeill and District Hospital', + 'Powell River General Hospital', + 'Prince Rupert Regional Hospital', + 'Princeton General Hospital', + 'Priory Hospital', + 'Queen Charlotte Islands General Hospital', + 'Queen Victoria Hospital', + 'R.W. Large Memorial Hospital', + 'Richmond Hospital', + 'Ridge Meadows Hospital & Health Care Centre', + 'Riverview Hospital', + 'Royal Columbian Hospital', + 'Royal Inland Hospital', + 'Royal Jubilee Hospital', + 'Saanich Peninsula Hospital', + 'Shuswap Lake General Hospital', + 'Slocan Community Health Centre', + 'South Okanagan General Hospital', + 'Sparwood Health Centre', + 'Squamish General Hospital', "St. Bartholomew's Hospital", - "St. John Hospital", + 'St. John Hospital', "St. Joseph's Hospital (see also Mount Saint Joseph Hospital above)", "St. Mary's Hospital", "St. Paul's Hospital", - "Stewart Health Centre", - "Stuart Lake General Hospital", - "Summerland Health Centre", - "Sunny Hill Health Centre for Children", - "Surrey Memorial Hospital", - "Tofino General Hospital", - "Trillium Lodge", - "UBC Hospital", - "University Hospital of Northern British Columbia", - "Vancouver General Hospital", - "Vancouver Hospital and Health Sciences Centre", - "Vernon Jubilee Hospital", - "Victoria General Hospital", - "Victorian Community Health Centre of Kaslo", - "West Coast General Hospital", - "Whistler Health Care Centre", - "Wrinch Memorial Hospital", + 'Stewart Health Centre', + 'Stuart Lake General Hospital', + 'Summerland Health Centre', + 'Sunny Hill Health Centre for Children', + 'Surrey Memorial Hospital', + 'Tofino General Hospital', + 'Trillium Lodge', + 'UBC Hospital', + 'University Hospital of Northern British Columbia', + 'Vancouver General Hospital', + 'Vancouver Hospital and Health Sciences Centre', + 'Vernon Jubilee Hospital', + 'Victoria General Hospital', + 'Victorian Community Health Centre of Kaslo', + 'West Coast General Hospital', + 'Whistler Health Care Centre', + 'Wrinch Memorial Hospital' ]; diff --git a/vsd-app/ClientApp/src/app/shared/introduction/introduction.component.scss b/vsd-app/ClientApp/src/app/shared/introduction/introduction.component.scss index c62175b8..14fb6d92 100644 --- a/vsd-app/ClientApp/src/app/shared/introduction/introduction.component.scss +++ b/vsd-app/ClientApp/src/app/shared/introduction/introduction.component.scss @@ -13,4 +13,4 @@ h2, h3 { margin-top: 30px; margin-bottom: 20px; -} \ No newline at end of file +} diff --git a/vsd-app/ClientApp/src/app/shared/introduction/introduction.component.ts b/vsd-app/ClientApp/src/app/shared/introduction/introduction.component.ts index 72ac706a..3bfbae11 100644 --- a/vsd-app/ClientApp/src/app/shared/introduction/introduction.component.ts +++ b/vsd-app/ClientApp/src/app/shared/introduction/introduction.component.ts @@ -1,74 +1,73 @@ -import { FormBase } from "../form-base"; -import { OnInit, Component, Input } from "@angular/core"; -import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS, MatDialog } from "@angular/material"; -import { FormGroup, ControlContainer } from "@angular/forms"; -import { MomentDateAdapter } from "@angular/material-moment-adapter"; -import { MY_FORMATS, ApplicationType } from "../enums-list"; -import { SummaryOfBenefitsDialog } from "../../summary-of-benefits/summary-of-benefits.component"; -import { LookupService } from "../../services/lookup.service"; +import { FormBase } from '../form-base'; +import { OnInit, Component, Input } from '@angular/core'; +import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS, MatDialog } from '@angular/material'; +import { FormGroup, ControlContainer } from '@angular/forms'; +import { MomentDateAdapter } from '@angular/material-moment-adapter'; +import { MY_FORMATS, ApplicationType } from '../enums-list'; +import { SummaryOfBenefitsDialog } from '../../summary-of-benefits/summary-of-benefits.component'; +import { LookupService } from '../../services/lookup.service'; @Component({ - selector: 'app-introduction', - templateUrl: './introduction.component.html', - styleUrls: ['./introduction.component.scss'], - providers: [ - // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your - // application's root module. We provide it at the component level here, due to limitations of - // our example generation script. - { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, - { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }, - ], + selector: 'app-introduction', + templateUrl: './introduction.component.html', + styleUrls: ['./introduction.component.scss'], + providers: [ + // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your + // application's root module. We provide it at the component level here, due to limitations of + // our example generation script. + { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, + { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS } + ] }) export class IntroductionComponent extends FormBase implements OnInit { - @Input() formType: number; - public form: FormGroup; - ApplicationType = ApplicationType; - applicant: string = ""; + @Input() formType: number; + public form: FormGroup; + ApplicationType = ApplicationType; + applicant: string = ''; - isIE: boolean = false; - cvapEmail: string = ""; - cvapCounsellingEmail: string = ""; + isIE: boolean = false; + cvapEmail: string = ''; + cvapCounsellingEmail: string = ''; - constructor( - private controlContainer: ControlContainer, - private matDialog: MatDialog, - private lookupService: LookupService, - ) { - super(); - } - - ngOnInit() { - var ua = window.navigator.userAgent; - this.isIE = /MSIE|Trident/.test(ua); + constructor( + private controlContainer: ControlContainer, + private matDialog: MatDialog, + private lookupService: LookupService + ) { + super(); + } - this.form = this.controlContainer.control; - setTimeout(() => { this.form.markAsTouched(); }, 0); - // console.log("intro component"); - // console.log(this.form); + ngOnInit() { + var ua = window.navigator.userAgent; + this.isIE = /MSIE|Trident/.test(ua); - if (this.formType === ApplicationType.Victim_Application) { - this.applicant = "Victims"; - } - else if (this.formType === ApplicationType.IFM_Application) { - this.applicant = "Immediate Family Members"; - } - else if (this.formType === ApplicationType.Witness_Application) { - this.applicant = "Witnesses"; - } + this.form = this.controlContainer.control; + setTimeout(() => { + this.form.markAsTouched(); + }, 0); + // console.log("intro component"); + // console.log(this.form); - if (this.lookupService.cvapEmail) { - this.cvapEmail = this.lookupService.cvapEmail; - this.cvapCounsellingEmail = this.lookupService.cvapCounsellingEmail; - } - else { - this.lookupService.getCVAPEmails().subscribe((res) => { - this.cvapEmail = res.cvapEmail; - this.cvapCounsellingEmail = res.cvapCounsellingEmail; - }); - } + if (this.formType === ApplicationType.Victim_Application) { + this.applicant = 'Victims'; + } else if (this.formType === ApplicationType.IFM_Application) { + this.applicant = 'Immediate Family Members'; + } else if (this.formType === ApplicationType.Witness_Application) { + this.applicant = 'Witnesses'; } - showSummaryOfBenefits(): void { - const summaryDialogRef = this.matDialog.open(SummaryOfBenefitsDialog, { data: this.formType }); + if (this.lookupService.cvapEmail) { + this.cvapEmail = this.lookupService.cvapEmail; + this.cvapCounsellingEmail = this.lookupService.cvapCounsellingEmail; + } else { + this.lookupService.getCVAPEmails().subscribe((res) => { + this.cvapEmail = res.cvapEmail; + this.cvapCounsellingEmail = res.cvapCounsellingEmail; + }); } -} \ No newline at end of file + } + + showSummaryOfBenefits(): void { + const summaryDialogRef = this.matDialog.open(SummaryOfBenefitsDialog, { data: this.formType }); + } +} diff --git a/vsd-app/ClientApp/src/app/shared/medical-information/medical-information.component.ts b/vsd-app/ClientApp/src/app/shared/medical-information/medical-information.component.ts index dfe29cc1..f1445012 100644 --- a/vsd-app/ClientApp/src/app/shared/medical-information/medical-information.component.ts +++ b/vsd-app/ClientApp/src/app/shared/medical-information/medical-information.component.ts @@ -1,287 +1,305 @@ -import { OnInit, Component, Input, OnDestroy } from "@angular/core"; -import { FormBase } from "../form-base"; -import { MatDialog, DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS } from "@angular/material"; -import { FormArray, FormGroup, Validators, FormBuilder, ControlContainer, FormControl, AbstractControl } from "@angular/forms"; -import { MomentDateAdapter } from "@angular/material-moment-adapter"; -import { MY_FORMATS, ApplicationType, CRMBoolean } from "../enums-list"; -import { COUNTRIES_ADDRESS } from "../address/country-list"; -import { HOSPITALS } from "../hospital-list"; -import { POSTAL_CODE } from "../regex.constants"; -import { AddressHelper } from "../address/address.helper"; -import { iLookupData } from "../../interfaces/lookup-data.interface"; -import { Subscription } from "rxjs"; -import { config } from "../../../config"; +import { OnInit, Component, Input, OnDestroy } from '@angular/core'; +import { FormBase } from '../form-base'; +import { MatDialog, DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS } from '@angular/material'; +import { + FormArray, + FormGroup, + Validators, + FormBuilder, + ControlContainer, + FormControl, + AbstractControl +} from '@angular/forms'; +import { MomentDateAdapter } from '@angular/material-moment-adapter'; +import { MY_FORMATS, ApplicationType, CRMBoolean } from '../enums-list'; +import { COUNTRIES_ADDRESS } from '../address/country-list'; +import { HOSPITALS } from '../hospital-list'; +import { POSTAL_CODE } from '../regex.constants'; +import { AddressHelper } from '../address/address.helper'; +import { iLookupData } from '../../interfaces/lookup-data.interface'; +import { Subscription } from 'rxjs'; +import { config } from '../../../config'; @Component({ - selector: 'app-medical-information', - templateUrl: './medical-information.component.html', - styleUrls: ['./medical-information.component.scss'], - providers: [ - // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your - // application's root module. We provide it at the component level here, due to limitations of - // our example generation script. - { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, - { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }, - ], + selector: 'app-medical-information', + templateUrl: './medical-information.component.html', + styleUrls: ['./medical-information.component.scss'], + providers: [ + // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your + // application's root module. We provide it at the component level here, due to limitations of + // our example generation script. + { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, + { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS } + ] }) export class MedicalInformationComponent extends FormBase implements OnInit, OnDestroy { - @Input() formType: number; - @Input() lookupData: iLookupData; - public form: FormGroup; - ApplicationType = ApplicationType; - CRMBoolean = CRMBoolean; + @Input() formType: number; + @Input() lookupData: iLookupData; + public form: FormGroup; + ApplicationType = ApplicationType; + CRMBoolean = CRMBoolean; - familyDoctorClinicItem: FormControl; + familyDoctorClinicItem: FormControl; - otherTreatmentItems: FormArray; - showAddProvider: boolean = true; - showRemoveProvider: boolean = false; + otherTreatmentItems: FormArray; + showAddProvider: boolean = true; + showRemoveProvider: boolean = false; - provinceList: string[] = []; - hospitalList = HOSPITALS; - postalRegex = POSTAL_CODE; + provinceList: string[] = []; + hospitalList = HOSPITALS; + postalRegex = POSTAL_CODE; - today = new Date(); + today = new Date(); - otherTreatmentLabel: string = ""; + otherTreatmentLabel: string = ''; - addressHelper = new AddressHelper(); + addressHelper = new AddressHelper(); - phoneMinLength: number = 10; - phoneMaxLength: number = 15; + phoneMinLength: number = 10; + phoneMaxLength: number = 15; - doctorAddressSubscription: Subscription; - wereYouTreatedAtHospitalSubscription: Subscription; - treatedOutsideBcSubscription: Subscription; + doctorAddressSubscription: Subscription; + wereYouTreatedAtHospitalSubscription: Subscription; + treatedOutsideBcSubscription: Subscription; - constructor( - private controlContainer: ControlContainer, - private matDialog: MatDialog, - private fb: FormBuilder, - ) { - super(); - } - - ngOnInit() { - this.form = this.controlContainer.control; - setTimeout(() => { this.form.markAsTouched(); }, 0); - // console.log("medical info component"); - // console.log(this.form); - - if (this.formType === ApplicationType.Victim_Application) { - this.otherTreatmentLabel = "Have you seen any other doctors, specialists, or counsellors who have been treating you for injuries resulting from the incident?"; - } - else { - this.otherTreatmentLabel = "Do you have a counsellor/therapist who has been treating you as a result of the incident?"; - } + constructor(private controlContainer: ControlContainer, private matDialog: MatDialog, private fb: FormBuilder) { + super(); + } - if (this.formType === ApplicationType.Victim_Application) { - this.wereYouTreatedAtHospitalSubscription = this.form.get('wereYouTreatedAtHospital').valueChanges.subscribe(value => { - let hospitalControl = this.form.get('treatedAtHospitalName'); - let options = { onlySelf: true, emitEvent: false }; - - // hospitalControl.clearValidators(); - // hospitalControl.setErrors(null); - - let useValidation = value === true; - if (useValidation) { - this.setControlValidators(hospitalControl, [Validators.required]); - // hospitalControl.setValidators(); - } - else { - this.clearControlValidators(hospitalControl); - hospitalControl.patchValue(''); - - let treatedOutsideBCControl = this.form.get('treatedOutsideBc'); - treatedOutsideBCControl.patchValue(false, options); - - let outsideBCHospitalControl = this.form.get('treatedOutsideBcHospitalName'); - outsideBCHospitalControl.clearValidators(); - outsideBCHospitalControl.setErrors(null); - outsideBCHospitalControl.patchValue(''); - - let treatedAtHospitalDateControl = this.form.get('treatedAtHospitalDate'); - treatedAtHospitalDateControl.patchValue(''); - } - - // hospitalControl.updateValueAndValidity(); - }); - - this.treatedOutsideBcSubscription = this.form.get('treatedOutsideBc').valueChanges.subscribe(value => { - let hospitalControl = this.form.get('treatedAtHospitalName'); - let outsideBCHospitalControl = this.form.get('treatedOutsideBcHospitalName'); - - if (value === true) { - this.clearControlValidators(hospitalControl); - outsideBCHospitalControl.setValidators([Validators.required]); - // hospitalControl.clearValidators(); - hospitalControl.setErrors(null); - hospitalControl.patchValue(''); - } - else { - this.setControlValidators(hospitalControl, [Validators.required]); - // hospitalControl.setValidators([Validators.required]); - outsideBCHospitalControl.clearValidators(); - outsideBCHospitalControl.setErrors(null); - } - hospitalControl.updateValueAndValidity(); - outsideBCHospitalControl.updateValueAndValidity(); - - }); - } + ngOnInit() { + this.form = this.controlContainer.control; + setTimeout(() => { + this.form.markAsTouched(); + }, 0); + // console.log("medical info component"); + // console.log(this.form); - this.doctorAddressSubscription = this.form.get('familyDoctorAddress').valueChanges.subscribe(value => { - this.setDoctorPhoneValidators(); - }); - - this.provinceList = this.lookupData.provinces.filter(p => p._vsd_countryid_value == config.canada_crm_id) - .map(p => p.vsd_name) - .sort((a, b) => a.localeCompare(b)); + if (this.formType === ApplicationType.Victim_Application) { + this.otherTreatmentLabel = + 'Have you seen any other doctors, specialists, or counsellors who have been treating you for injuries resulting from the incident?'; + } else { + this.otherTreatmentLabel = + 'Do you have a counsellor/therapist who has been treating you as a result of the incident?'; } - ngOnDestroy() { - if (this.doctorAddressSubscription) this.doctorAddressSubscription.unsubscribe(); - if (this.wereYouTreatedAtHospitalSubscription) this.wereYouTreatedAtHospitalSubscription.unsubscribe(); - if (this.treatedOutsideBcSubscription) this.treatedOutsideBcSubscription.unsubscribe(); - } + if (this.formType === ApplicationType.Victim_Application) { + this.wereYouTreatedAtHospitalSubscription = this.form + .get('wereYouTreatedAtHospital') + .valueChanges.subscribe((value) => { + let hospitalControl = this.form.get('treatedAtHospitalName'); + let options = { onlySelf: true, emitEvent: false }; + + // hospitalControl.clearValidators(); + // hospitalControl.setErrors(null); + + let useValidation = value === true; + if (useValidation) { + this.setControlValidators(hospitalControl, [Validators.required]); + // hospitalControl.setValidators(); + } else { + this.clearControlValidators(hospitalControl); + hospitalControl.patchValue(''); + + let treatedOutsideBCControl = this.form.get('treatedOutsideBc'); + treatedOutsideBCControl.patchValue(false, options); + + let outsideBCHospitalControl = this.form.get('treatedOutsideBcHospitalName'); + outsideBCHospitalControl.clearValidators(); + outsideBCHospitalControl.setErrors(null); + outsideBCHospitalControl.patchValue(''); + + let treatedAtHospitalDateControl = this.form.get('treatedAtHospitalDate'); + treatedAtHospitalDateControl.patchValue(''); + } + + // hospitalControl.updateValueAndValidity(); + }); - addProvider(): void { - // add a medical treatment provider to the list - this.otherTreatmentItems = this.form.get('otherTreatments') as FormArray; - let thisTreatment = this.createTreatmentItem(); - this.otherTreatmentItems.push(thisTreatment); - this.showAddProvider = this.otherTreatmentItems.length < 5; - this.showRemoveProvider = this.otherTreatmentItems.length > 1; - } - clearProviders(): void { - // remove all providers - this.otherTreatmentItems = this.form.get('otherTreatments') as FormArray; - while (this.otherTreatmentItems.length > 0) { - this.otherTreatmentItems.removeAt(this.otherTreatmentItems.length - 1); + this.treatedOutsideBcSubscription = this.form.get('treatedOutsideBc').valueChanges.subscribe((value) => { + let hospitalControl = this.form.get('treatedAtHospitalName'); + let outsideBCHospitalControl = this.form.get('treatedOutsideBcHospitalName'); + + if (value === true) { + this.clearControlValidators(hospitalControl); + outsideBCHospitalControl.setValidators([Validators.required]); + // hospitalControl.clearValidators(); + hospitalControl.setErrors(null); + hospitalControl.patchValue(''); + } else { + this.setControlValidators(hospitalControl, [Validators.required]); + // hospitalControl.setValidators([Validators.required]); + outsideBCHospitalControl.clearValidators(); + outsideBCHospitalControl.setErrors(null); } + hospitalControl.updateValueAndValidity(); + outsideBCHospitalControl.updateValueAndValidity(); + }); } - removeProvider(index: number): void { - // when the user clicks to remove the medical provider this removes the provider at the index clicked - this.otherTreatmentItems = this.form.get('otherTreatments') as FormArray; - this.otherTreatmentItems.removeAt(index); - this.showAddProvider = this.otherTreatmentItems.length < 5; - this.showRemoveProvider = this.otherTreatmentItems.length > 1; + this.doctorAddressSubscription = this.form.get('familyDoctorAddress').valueChanges.subscribe((value) => { + this.setDoctorPhoneValidators(); + }); + + this.provinceList = this.lookupData.provinces + .filter((p) => p._vsd_countryid_value == config.canada_crm_id) + .map((p) => p.vsd_name) + .sort((a, b) => a.localeCompare(b)); + } + + ngOnDestroy() { + if (this.doctorAddressSubscription) this.doctorAddressSubscription.unsubscribe(); + if (this.wereYouTreatedAtHospitalSubscription) this.wereYouTreatedAtHospitalSubscription.unsubscribe(); + if (this.treatedOutsideBcSubscription) this.treatedOutsideBcSubscription.unsubscribe(); + } + + addProvider(): void { + // add a medical treatment provider to the list + this.otherTreatmentItems = this.form.get('otherTreatments') as FormArray; + let thisTreatment = this.createTreatmentItem(); + this.otherTreatmentItems.push(thisTreatment); + this.showAddProvider = this.otherTreatmentItems.length < 5; + this.showRemoveProvider = this.otherTreatmentItems.length > 1; + } + clearProviders(): void { + // remove all providers + this.otherTreatmentItems = this.form.get('otherTreatments') as FormArray; + while (this.otherTreatmentItems.length > 0) { + this.otherTreatmentItems.removeAt(this.otherTreatmentItems.length - 1); } - - createTreatmentItem(): FormGroup { - let group = { - providerCompany: [''], - providerEmail: ['', [Validators.email]], - providerFirstName: [''], - providerLastName: [''], - providerPhoneNumber: [''], - providerFax: [''], - providerAddress: this.fb.group({ - line1: [''], - line2: [''], - city: [''], - postalCode: ['', [Validators.pattern(this.postalRegex)]], - province: [{ value: 'British Columbia', disabled: false }], - country: [{ value: 'Canada', disabled: false }], - }), - }; - - if (this.formType === ApplicationType.Victim_Application) { - group['providerType'] = ['', Validators.required]; - group['providerTypeText'] = ['']; - } - else { - group['providerType'] = ['Counsellor'] - } - - return this.fb.group(group); + } + + removeProvider(index: number): void { + // when the user clicks to remove the medical provider this removes the provider at the index clicked + this.otherTreatmentItems = this.form.get('otherTreatments') as FormArray; + this.otherTreatmentItems.removeAt(index); + this.showAddProvider = this.otherTreatmentItems.length < 5; + this.showRemoveProvider = this.otherTreatmentItems.length > 1; + } + + createTreatmentItem(): FormGroup { + let group = { + providerCompany: [''], + providerEmail: ['', [Validators.email]], + providerFirstName: [''], + providerLastName: [''], + providerPhoneNumber: [''], + providerFax: [''], + providerAddress: this.fb.group({ + line1: [''], + line2: [''], + city: [''], + postalCode: ['', [Validators.pattern(this.postalRegex)]], + province: [{ value: 'British Columbia', disabled: false }], + country: [{ value: 'Canada', disabled: false }] + }) + }; + + if (this.formType === ApplicationType.Victim_Application) { + group['providerType'] = ['', Validators.required]; + group['providerTypeText'] = ['']; + } else { + group['providerType'] = ['Counsellor']; } - addDoctor(): void { - this.familyDoctorClinicItem = this.form.get('familyDoctorClinic') as FormControl; - this.familyDoctorClinicItem.setValidators([Validators.required]); - this.familyDoctorClinicItem.updateValueAndValidity(); + return this.fb.group(group); + } + + addDoctor(): void { + this.familyDoctorClinicItem = this.form.get('familyDoctorClinic') as FormControl; + this.familyDoctorClinicItem.setValidators([Validators.required]); + this.familyDoctorClinicItem.updateValueAndValidity(); + } + + clearDoctor(): void { + this.familyDoctorClinicItem = this.form.get('familyDoctorClinic') as FormControl; + this.familyDoctorClinicItem.clearValidators(); + this.familyDoctorClinicItem.updateValueAndValidity(); + + this.familyDoctorClinicItem.patchValue(''); + let doctorFirstNameControl = this.form.get('familyDoctorFirstName'); + doctorFirstNameControl.patchValue(''); + + let doctorLastNameControl = this.form.get('familyDoctorLastName'); + doctorLastNameControl.patchValue(''); + + let doctorEmailControl = this.form.get('familyDoctorEmail'); + doctorEmailControl.patchValue(''); + + let doctorPhoneControl = this.form.get('familyDoctorPhoneNumber'); + doctorPhoneControl.patchValue(''); + + let doctorFaxControl = this.form.get('familyDoctorFax'); + doctorFaxControl.patchValue(''); + + this.addressHelper.clearAddress(this.form, 'familyDoctorAddress'); + this.addressHelper.clearAddressValidatorsAndErrors(this.form, 'familyDoctorAddress'); + } + + doYouHaveMedicalServicesCoverageChange(val) { + let haveMedicalCoverageProvinceControl = this.form.get('haveMedicalCoverageProvince'); + let haveMedicalCoverageProvinceOtherControl = this.form.get('haveMedicalCoverageProvinceOther'); + let personalHealthNumberControl = this.form.get('personalHealthNumber'); + + if (val) { + haveMedicalCoverageProvinceControl.patchValue('British Columbia'); + this.setControlValidators(haveMedicalCoverageProvinceControl, [Validators.required]); + } else { + this.clearControlValidators(haveMedicalCoverageProvinceControl); + haveMedicalCoverageProvinceControl.patchValue(''); + haveMedicalCoverageProvinceOtherControl.patchValue(''); + personalHealthNumberControl.patchValue(''); } + } - clearDoctor(): void { - this.familyDoctorClinicItem = this.form.get('familyDoctorClinic') as FormControl; - this.familyDoctorClinicItem.clearValidators(); - this.familyDoctorClinicItem.updateValueAndValidity(); - - this.familyDoctorClinicItem.patchValue(''); - let doctorFirstNameControl = this.form.get('familyDoctorFirstName'); - doctorFirstNameControl.patchValue(''); - - let doctorLastNameControl = this.form.get('familyDoctorLastName'); - doctorLastNameControl.patchValue(''); - - let doctorEmailControl = this.form.get('familyDoctorEmail'); - doctorEmailControl.patchValue(''); + doYouHaveOtherHealthCoverageChange(val: boolean) { + let otherHealthCoverageProviderNameControl = this.form.get('otherHealthCoverageProviderName'); + let otherHealthCoverageExtendedPlanNumberControl = this.form.get('otherHealthCoverageExtendedPlanNumber'); - let doctorPhoneControl = this.form.get('familyDoctorPhoneNumber'); - doctorPhoneControl.patchValue(''); - - let doctorFaxControl = this.form.get('familyDoctorFax'); - doctorFaxControl.patchValue(''); - - this.addressHelper.clearAddress(this.form, 'familyDoctorAddress'); - this.addressHelper.clearAddressValidatorsAndErrors(this.form, 'familyDoctorAddress'); + if (!val) { + otherHealthCoverageProviderNameControl.patchValue(''); + otherHealthCoverageExtendedPlanNumberControl.patchValue(''); } + } - doYouHaveMedicalServicesCoverageChange(val) { - let haveMedicalCoverageProvinceControl = this.form.get('haveMedicalCoverageProvince'); - let haveMedicalCoverageProvinceOtherControl = this.form.get('haveMedicalCoverageProvinceOther'); - let personalHealthNumberControl = this.form.get('personalHealthNumber'); - - if (val) { - haveMedicalCoverageProvinceControl.patchValue('British Columbia'); - this.setControlValidators(haveMedicalCoverageProvinceControl, [Validators.required]); - } - else { - this.clearControlValidators(haveMedicalCoverageProvinceControl); - haveMedicalCoverageProvinceControl.patchValue(''); - haveMedicalCoverageProvinceOtherControl.patchValue(''); - personalHealthNumberControl.patchValue(''); - } - } - - doYouHaveOtherHealthCoverageChange(val: boolean) { - let otherHealthCoverageProviderNameControl = this.form.get('otherHealthCoverageProviderName'); - let otherHealthCoverageExtendedPlanNumberControl = this.form.get('otherHealthCoverageExtendedPlanNumber'); - - if (!val) { - otherHealthCoverageProviderNameControl.patchValue(''); - otherHealthCoverageExtendedPlanNumberControl.patchValue(''); - } + setDoctorPhoneValidators() { + if ( + this.form.get('familyDoctorAddress.country').value === 'Canada' || + this.form.get('familyDoctorAddress.country').value === 'United States of America' + ) { + this.phoneMinLength = 10; + } else { + this.phoneMinLength = 8; } - setDoctorPhoneValidators() { - if (this.form.get('familyDoctorAddress.country').value === 'Canada' || this.form.get('familyDoctorAddress.country').value === 'United States of America') { - this.phoneMinLength = 10; - } - else { - this.phoneMinLength = 8; - } - - let phoneControl = this.form.get('familyDoctorPhoneNumber'); - this.setControlValidators(phoneControl, [Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - phoneControl.patchValue(phoneControl.value); + let phoneControl = this.form.get('familyDoctorPhoneNumber'); + this.setControlValidators(phoneControl, [ + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + phoneControl.patchValue(phoneControl.value); + } + + setProviderPhoneValidators(provider: AbstractControl) { + if ( + provider.get('providerAddress.country').value === 'Canada' || + provider.get('providerAddress.country').value === 'United States of America' + ) { + this.phoneMinLength = 10; + } else { + this.phoneMinLength = 8; } - setProviderPhoneValidators(provider: AbstractControl) { - if (provider.get('providerAddress.country').value === 'Canada' || provider.get('providerAddress.country').value === 'United States of America') { - this.phoneMinLength = 10; - } - else { - this.phoneMinLength = 8; - } - - let phoneControl = provider.get('providerPhoneNumber'); - let faxControl = provider.get('providerFax'); - this.setControlValidators(phoneControl, [Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - this.setControlValidators(faxControl, [Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - phoneControl.patchValue(phoneControl.value); - faxControl.patchValue(faxControl.value); - } + let phoneControl = provider.get('providerPhoneNumber'); + let faxControl = provider.get('providerFax'); + this.setControlValidators(phoneControl, [ + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + this.setControlValidators(faxControl, [ + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + phoneControl.patchValue(phoneControl.value); + faxControl.patchValue(faxControl.value); + } } diff --git a/vsd-app/ClientApp/src/app/shared/medical-information/medical-information.helper.ts b/vsd-app/ClientApp/src/app/shared/medical-information/medical-information.helper.ts index 39a40f45..83976d53 100644 --- a/vsd-app/ClientApp/src/app/shared/medical-information/medical-information.helper.ts +++ b/vsd-app/ClientApp/src/app/shared/medical-information/medical-information.helper.ts @@ -1,50 +1,50 @@ -import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms"; -import { ApplicationType } from "../enums-list"; -import { POSTAL_CODE } from "../regex.constants"; +import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms'; +import { ApplicationType } from '../enums-list'; +import { POSTAL_CODE } from '../regex.constants'; export class MedicalInfoHelper { - postalRegex = POSTAL_CODE; - public setupFormGroup(fb: FormBuilder, form_type: ApplicationType): FormGroup { - let group = { - doYouHaveMedicalServicesCoverage: ['', Validators.required], - haveMedicalCoverageProvince: ['British Columbia'], - haveMedicalCoverageProvinceOther: [''], - personalHealthNumber: [''], + postalRegex = POSTAL_CODE; + public setupFormGroup(fb: FormBuilder, form_type: ApplicationType): FormGroup { + let group = { + doYouHaveMedicalServicesCoverage: ['', Validators.required], + haveMedicalCoverageProvince: ['British Columbia'], + haveMedicalCoverageProvinceOther: [''], + personalHealthNumber: [''], - doYouHaveOtherHealthCoverage: ['', Validators.required], - otherHealthCoverageProviderName: [''], - otherHealthCoverageExtendedPlanNumber: [''], + doYouHaveOtherHealthCoverage: ['', Validators.required], + otherHealthCoverageProviderName: [''], + otherHealthCoverageExtendedPlanNumber: [''], - beingTreatedByFamilyDoctor: ['', Validators.required], - familyDoctorClinic: [''], - familyDoctorFirstName: [''], - familyDoctorLastName: [''], - familyDoctorEmail: ['', [Validators.email]], - familyDoctorPhoneNumber: [''], - familyDoctorFax: [''], - familyDoctorAddress: fb.group({ - line1: [''], - line2: [''], - city: [''], - postalCode: ['', [Validators.pattern(this.postalRegex)]], - province: [{ value: 'British Columbia', disabled: false }], - country: [{ value: 'Canada', disabled: false }], - }), - // familyDoctorAddressLine1: [''], - // familyDoctorAddressLine2: [''], + beingTreatedByFamilyDoctor: ['', Validators.required], + familyDoctorClinic: [''], + familyDoctorFirstName: [''], + familyDoctorLastName: [''], + familyDoctorEmail: ['', [Validators.email]], + familyDoctorPhoneNumber: [''], + familyDoctorFax: [''], + familyDoctorAddress: fb.group({ + line1: [''], + line2: [''], + city: [''], + postalCode: ['', [Validators.pattern(this.postalRegex)]], + province: [{ value: 'British Columbia', disabled: false }], + country: [{ value: 'Canada', disabled: false }] + }), + // familyDoctorAddressLine1: [''], + // familyDoctorAddressLine2: [''], - hadOtherTreatments: ['', Validators.required], - otherTreatments: fb.array([]), - }; + hadOtherTreatments: ['', Validators.required], + otherTreatments: fb.array([]) + }; - if (form_type === ApplicationType.Victim_Application) { - group['wereYouTreatedAtHospital'] = ['', Validators.required]; - group['treatedAtHospitalName'] = ['']; - group['treatedOutsideBc'] = [false]; - group['treatedOutsideBcHospitalName'] = ['']; - group['treatedAtHospitalDate'] = ['']; - } - - return fb.group(group); + if (form_type === ApplicationType.Victim_Application) { + group['wereYouTreatedAtHospital'] = ['', Validators.required]; + group['treatedAtHospitalName'] = ['']; + group['treatedOutsideBc'] = [false]; + group['treatedOutsideBcHospitalName'] = ['']; + group['treatedAtHospitalDate'] = ['']; } + + return fb.group(group); + } } diff --git a/vsd-app/ClientApp/src/app/shared/personal-information/personal-information.component.scss b/vsd-app/ClientApp/src/app/shared/personal-information/personal-information.component.scss index c542db05..c458f7cb 100644 --- a/vsd-app/ClientApp/src/app/shared/personal-information/personal-information.component.scss +++ b/vsd-app/ClientApp/src/app/shared/personal-information/personal-information.component.scss @@ -224,8 +224,8 @@ input.form-control { margin-bottom: 5px; } - input[type="checkbox"], - input[type="radio"] { + input[type='checkbox'], + input[type='radio'] { margin-right: 5px; } @@ -248,7 +248,7 @@ input.form-control { } ::ng-deep .terms { - input[type="text"] { + input[type='text'] { margin-left: 15px; } diff --git a/vsd-app/ClientApp/src/app/shared/personal-information/personal-information.component.ts b/vsd-app/ClientApp/src/app/shared/personal-information/personal-information.component.ts index 7e6a8a21..c24a800a 100644 --- a/vsd-app/ClientApp/src/app/shared/personal-information/personal-information.component.ts +++ b/vsd-app/ClientApp/src/app/shared/personal-information/personal-information.component.ts @@ -1,312 +1,405 @@ -import { OnInit, Component, Input, OnDestroy } from "@angular/core"; -import { FormBase } from "../form-base"; -import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS } from "@angular/material"; -import { FormGroup, ControlContainer, AbstractControl, Validators } from "@angular/forms"; -import { MomentDateAdapter } from "@angular/material-moment-adapter"; -import { MY_FORMATS, ApplicationType } from "../enums-list"; -import { POSTAL_CODE } from "../regex.constants"; -import { AddressHelper } from "../address/address.helper"; -import { EmailValidator } from "../validators/email.validator"; -import { Subscription } from "rxjs"; -import { iLookupData } from "../../interfaces/lookup-data.interface"; +import { OnInit, Component, Input, OnDestroy } from '@angular/core'; +import { FormBase } from '../form-base'; +import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS } from '@angular/material'; +import { FormGroup, ControlContainer, AbstractControl, Validators } from '@angular/forms'; +import { MomentDateAdapter } from '@angular/material-moment-adapter'; +import { MY_FORMATS, ApplicationType } from '../enums-list'; +import { POSTAL_CODE } from '../regex.constants'; +import { AddressHelper } from '../address/address.helper'; +import { EmailValidator } from '../validators/email.validator'; +import { Subscription } from 'rxjs'; +import { iLookupData } from '../../interfaces/lookup-data.interface'; @Component({ - selector: 'app-personal-information', - templateUrl: './personal-information.component.html', - styleUrls: ['./personal-information.component.scss'], - providers: [ - // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your - // application's root module. We provide it at the component level here, due to limitations of - // our example generation script. - { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, - { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }, - ], + selector: 'app-personal-information', + templateUrl: './personal-information.component.html', + styleUrls: ['./personal-information.component.scss'], + providers: [ + // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your + // application's root module. We provide it at the component level here, due to limitations of + // our example generation script. + { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, + { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS } + ] }) export class PersonalInformationComponent extends FormBase implements OnInit, OnDestroy { - @Input() formType: number; - @Input() lookupData: iLookupData; - public form: FormGroup; - ApplicationType = ApplicationType; - postalRegex = POSTAL_CODE; - - header: string; - - todaysDate = new Date(); // for the birthdate validation - oldestHuman = new Date(this.todaysDate.getFullYear() - 120, this.todaysDate.getMonth(), this.todaysDate.getDay()); - - phoneIsRequired: boolean = false; - isVoiceMailRequired: boolean = false; - emailIsRequired: boolean = false; - addressIsRequired: boolean = false; - alternateAddressIsRequired: boolean = false; - - addressHelper = new AddressHelper(); - - preferredMethodOfContactSubscription: Subscription; - sinSubscription: Subscription; - leaveVoicemailSubscription: Subscription; - addressSubscription: Subscription; - phoneSubscription: Subscription; - altPhoneSubscription: Subscription; - emailSubscription: Subscription; - confirmEmailSubscription: Subscription; - - phoneMinLength: number = 10; - phoneMaxLength: number = 15; - - get preferredMethodOfContact() { return this.form.get('preferredMethodOfContact'); } - get leaveVoicemail() { return this.form.get('leaveVoicemail'); } - - constructor( - private controlContainer: ControlContainer, - ) { - super(); + @Input() formType: number; + @Input() lookupData: iLookupData; + public form: FormGroup; + ApplicationType = ApplicationType; + postalRegex = POSTAL_CODE; + + header: string; + + todaysDate = new Date(); // for the birthdate validation + oldestHuman = new Date(this.todaysDate.getFullYear() - 120, this.todaysDate.getMonth(), this.todaysDate.getDay()); + + phoneIsRequired: boolean = false; + isVoiceMailRequired: boolean = false; + emailIsRequired: boolean = false; + addressIsRequired: boolean = false; + alternateAddressIsRequired: boolean = false; + + addressHelper = new AddressHelper(); + + preferredMethodOfContactSubscription: Subscription; + sinSubscription: Subscription; + leaveVoicemailSubscription: Subscription; + addressSubscription: Subscription; + phoneSubscription: Subscription; + altPhoneSubscription: Subscription; + emailSubscription: Subscription; + confirmEmailSubscription: Subscription; + + phoneMinLength: number = 10; + phoneMaxLength: number = 15; + + get preferredMethodOfContact() { + return this.form.get('preferredMethodOfContact'); + } + get leaveVoicemail() { + return this.form.get('leaveVoicemail'); + } + + constructor(private controlContainer: ControlContainer) { + super(); + } + + ngOnInit() { + this.form = this.controlContainer.control; + setTimeout(() => { + this.form.markAsTouched(); + }, 0); + // console.log("personal info component"); + // console.log(this.form); + + this.header = 'Personal'; + if (this.formType == ApplicationType.Victim_Application) { + this.header = 'Victim'; } - ngOnInit() { - this.form = this.controlContainer.control; - setTimeout(() => { this.form.markAsTouched(); }, 0); - // console.log("personal info component"); - // console.log(this.form); - - this.header = "Personal"; - if (this.formType == ApplicationType.Victim_Application) { - this.header = "Victim"; - } - - if (this.formType == ApplicationType.Victim_Application) { - this.addressSubscription = this.form.get('primaryAddress').valueChanges.subscribe(value => { - this.copyPersonalAddressToRepresentativeAddress(this.form.parent); - this.setPhoneValidators(); - this.setEmailValidators(); - }); - - this.phoneSubscription = this.form.get('phoneNumber').valueChanges.subscribe(value => { - this.copyPersonalContactInfoToRepresentative(this.form.parent); - }); - this.altPhoneSubscription = this.form.get('alternatePhoneNumber').valueChanges.subscribe(value => { - this.copyPersonalContactInfoToRepresentative(this.form.parent); - }); - this.emailSubscription = this.form.get('email').valueChanges.subscribe(value => { - this.copyPersonalContactInfoToRepresentative(this.form.parent); - }); - this.confirmEmailSubscription = this.form.get('confirmEmail').valueChanges.subscribe(value => { - this.copyPersonalContactInfoToRepresentative(this.form.parent); - }); - } - - if (this.formType == ApplicationType.IFM_Application || this.formType == ApplicationType.Witness_Application) { - this.addressSubscription = this.form.get('primaryAddress').valueChanges.subscribe(value => { - this.copyPersonalAddressToVictimAddress(this.form.parent); - this.copyPersonalAddressToRepresentativeAddress(this.form.parent); - this.setPhoneValidators(); - }); - - this.phoneSubscription = this.form.get('phoneNumber').valueChanges.subscribe(value => { - this.copyPersonalContactInfoToVictim(this.form.parent); - this.copyPersonalContactInfoToRepresentative(this.form.parent); - }); - this.altPhoneSubscription = this.form.get('alternatePhoneNumber').valueChanges.subscribe(value => { - this.copyPersonalContactInfoToVictim(this.form.parent); - this.copyPersonalContactInfoToRepresentative(this.form.parent); - }); - this.emailSubscription = this.form.get('email').valueChanges.subscribe(value => { - this.copyPersonalContactInfoToVictim(this.form.parent); - this.copyPersonalContactInfoToRepresentative(this.form.parent); - }); - this.confirmEmailSubscription = this.form.get('confirmEmail').valueChanges.subscribe(value => { - this.copyPersonalContactInfoToVictim(this.form.parent); - this.copyPersonalContactInfoToRepresentative(this.form.parent); - }); - } - - this.preferredMethodOfContactSubscription = this.form.get('preferredMethodOfContact').valueChanges.subscribe(value => this.preferredMethodOfContactChange(value)); - - if (this.formType == ApplicationType.Victim_Application || this.formType == ApplicationType.IFM_Application) { - this.sinSubscription = this.form.get('sin').valueChanges.subscribe((value) => { - if (value == null) value = ''; - let incomeForm = 'employmentIncomeInformation'; - if (this.formType == ApplicationType.IFM_Application) - incomeForm = 'expenseInformation'; - this.form.parent.get(incomeForm).get('sin').patchValue(value); - }); - } - - this.leaveVoicemailSubscription = this.form.get('leaveVoicemail').valueChanges.subscribe(value => { - let phoneControl = this.form.get('phoneNumber'); - let altPhoneControl = this.form.get('alternatePhoneNumber'); - //setup phone control validators based on preferredMethodOfContact - this.setControlValidators(phoneControl, [Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - this.setControlValidators(altPhoneControl, [Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - let contactMethod = this.form.get('preferredMethodOfContact').value; - if (contactMethod == 2) { //phone call - this.setControlValidators(phoneControl, [Validators.required, Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - } - //then update potentially update it based on voicemail selection - - let voicemailOption = parseInt(value); - if (voicemailOption == 100000000) { //Primary and Alternate - this.setControlValidators(phoneControl, [Validators.required, Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - this.setControlValidators(altPhoneControl, [Validators.required, Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - } - else if (voicemailOption == 100000001) { //Primary only - this.setControlValidators(phoneControl, [Validators.required, Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - } - else if (voicemailOption == 100000002) { //Alternate only - this.setControlValidators(altPhoneControl, [Validators.required, Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - } - }); + if (this.formType == ApplicationType.Victim_Application) { + this.addressSubscription = this.form.get('primaryAddress').valueChanges.subscribe((value) => { + this.copyPersonalAddressToRepresentativeAddress(this.form.parent); + this.setPhoneValidators(); + this.setEmailValidators(); + }); + + this.phoneSubscription = this.form.get('phoneNumber').valueChanges.subscribe((value) => { + this.copyPersonalContactInfoToRepresentative(this.form.parent); + }); + this.altPhoneSubscription = this.form.get('alternatePhoneNumber').valueChanges.subscribe((value) => { + this.copyPersonalContactInfoToRepresentative(this.form.parent); + }); + this.emailSubscription = this.form.get('email').valueChanges.subscribe((value) => { + this.copyPersonalContactInfoToRepresentative(this.form.parent); + }); + this.confirmEmailSubscription = this.form.get('confirmEmail').valueChanges.subscribe((value) => { + this.copyPersonalContactInfoToRepresentative(this.form.parent); + }); } - ngOnDestroy() { - if (this.preferredMethodOfContactSubscription) this.preferredMethodOfContactSubscription.unsubscribe(); - if (this.leaveVoicemailSubscription) this.leaveVoicemailSubscription.unsubscribe(); - if (this.sinSubscription) this.sinSubscription.unsubscribe(); - if (this.addressSubscription) this.addressSubscription.unsubscribe(); - if (this.phoneSubscription) this.phoneSubscription.unsubscribe(); - if (this.altPhoneSubscription) this.altPhoneSubscription.unsubscribe(); - if (this.emailSubscription) this.emailSubscription.unsubscribe(); - if (this.confirmEmailSubscription) this.confirmEmailSubscription.unsubscribe(); + if (this.formType == ApplicationType.IFM_Application || this.formType == ApplicationType.Witness_Application) { + this.addressSubscription = this.form.get('primaryAddress').valueChanges.subscribe((value) => { + this.copyPersonalAddressToVictimAddress(this.form.parent); + this.copyPersonalAddressToRepresentativeAddress(this.form.parent); + this.setPhoneValidators(); + }); + + this.phoneSubscription = this.form.get('phoneNumber').valueChanges.subscribe((value) => { + this.copyPersonalContactInfoToVictim(this.form.parent); + this.copyPersonalContactInfoToRepresentative(this.form.parent); + }); + this.altPhoneSubscription = this.form.get('alternatePhoneNumber').valueChanges.subscribe((value) => { + this.copyPersonalContactInfoToVictim(this.form.parent); + this.copyPersonalContactInfoToRepresentative(this.form.parent); + }); + this.emailSubscription = this.form.get('email').valueChanges.subscribe((value) => { + this.copyPersonalContactInfoToVictim(this.form.parent); + this.copyPersonalContactInfoToRepresentative(this.form.parent); + }); + this.confirmEmailSubscription = this.form.get('confirmEmail').valueChanges.subscribe((value) => { + this.copyPersonalContactInfoToVictim(this.form.parent); + this.copyPersonalContactInfoToRepresentative(this.form.parent); + }); } - preferredMethodOfContactChange(value) { - let phoneControl = this.form.get('phoneNumber'); - let altPhoneControl = this.form.get('alternatePhoneNumber'); - let emailControl = this.form.get('email'); - let emailConfirmControl = this.form.get('confirmEmail'); - let agreeToCVAPEmailControl = this.form.get('agreeToCvapCommunicationExchange'); - - this.addressHelper.clearAddressValidatorsAndErrors(this.form, 'primaryAddress'); - this.addressHelper.clearAddressValidatorsAndErrors(this.form, 'alternateAddress'); - this.addressHelper.setAddressAsRequired(this.form, 'primaryAddress'); - // this.addressHelper.markAsTouched(this.form, 'primaryAddress'); - - this.setControlValidators(phoneControl, [Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - this.setControlValidators(emailControl, [Validators.email]); - this.setControlValidators(emailConfirmControl, [Validators.email, EmailValidator('email')]); - this.clearControlValidators(agreeToCVAPEmailControl); - - let contactMethod = parseInt(value); - if (contactMethod == 2) { //phone call - this.setControlValidators(phoneControl, [Validators.required, Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - this.phoneIsRequired = true; - this.emailIsRequired = false; - this.addressIsRequired = false; - } else if (contactMethod == 1) { //Email - this.setControlValidators(emailControl, [Validators.required, Validators.email]); - this.setControlValidators(emailConfirmControl, [Validators.required, Validators.email, EmailValidator('email')]); - this.setControlValidators(agreeToCVAPEmailControl, [Validators.requiredTrue]); - this.phoneIsRequired = false; - this.emailIsRequired = true; - this.addressIsRequired = false; - } else if (contactMethod == 4) { //Mail - this.phoneIsRequired = false; - this.emailIsRequired = false; - this.addressIsRequired = true; - this.alternateAddressIsRequired = false; - } - - let voicemailOption = parseInt(this.form.get('leaveVoicemail').value); - if (voicemailOption == 100000000) { //Primary and Alternate - this.setControlValidators(phoneControl, [Validators.required, Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - this.setControlValidators(altPhoneControl, [Validators.required, Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - } - else if (voicemailOption == 100000001) { //Primary only - this.setControlValidators(phoneControl, [Validators.required, Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - } - else if (voicemailOption == 100000002) { //Alternate only - this.setControlValidators(altPhoneControl, [Validators.required, Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - } - - if (agreeToCVAPEmailControl.value == true) { - this.setControlValidators(emailControl, [Validators.required, Validators.email]); - this.setControlValidators(emailConfirmControl, [Validators.required, Validators.email, EmailValidator('email')]); - } - - //verify that email is marked as required per "Other" address rule - this.setEmailValidators(); + this.preferredMethodOfContactSubscription = this.form + .get('preferredMethodOfContact') + .valueChanges.subscribe((value) => this.preferredMethodOfContactChange(value)); + + if (this.formType == ApplicationType.Victim_Application || this.formType == ApplicationType.IFM_Application) { + this.sinSubscription = this.form.get('sin').valueChanges.subscribe((value) => { + if (value == null) value = ''; + let incomeForm = 'employmentIncomeInformation'; + if (this.formType == ApplicationType.IFM_Application) incomeForm = 'expenseInformation'; + this.form.parent.get(incomeForm).get('sin').patchValue(value); + }); } - iHaveOtherNamesChange(val: boolean) { - if (!val) { - let otherFirstNameControl = this.form.get('otherFirstName'); - let otherLastNameControl = this.form.get('otherLastName'); - let dateOfNameChangeControl = this.form.get('dateOfNameChange'); + this.leaveVoicemailSubscription = this.form.get('leaveVoicemail').valueChanges.subscribe((value) => { + let phoneControl = this.form.get('phoneNumber'); + let altPhoneControl = this.form.get('alternatePhoneNumber'); + //setup phone control validators based on preferredMethodOfContact + this.setControlValidators(phoneControl, [ + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + this.setControlValidators(altPhoneControl, [ + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + let contactMethod = this.form.get('preferredMethodOfContact').value; + if (contactMethod == 2) { + //phone call + this.setControlValidators(phoneControl, [ + Validators.required, + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + } + //then update potentially update it based on voicemail selection + + let voicemailOption = parseInt(value); + if (voicemailOption == 100000000) { + //Primary and Alternate + this.setControlValidators(phoneControl, [ + Validators.required, + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + this.setControlValidators(altPhoneControl, [ + Validators.required, + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + } else if (voicemailOption == 100000001) { + //Primary only + this.setControlValidators(phoneControl, [ + Validators.required, + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + } else if (voicemailOption == 100000002) { + //Alternate only + this.setControlValidators(altPhoneControl, [ + Validators.required, + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + } + }); + } + + ngOnDestroy() { + if (this.preferredMethodOfContactSubscription) this.preferredMethodOfContactSubscription.unsubscribe(); + if (this.leaveVoicemailSubscription) this.leaveVoicemailSubscription.unsubscribe(); + if (this.sinSubscription) this.sinSubscription.unsubscribe(); + if (this.addressSubscription) this.addressSubscription.unsubscribe(); + if (this.phoneSubscription) this.phoneSubscription.unsubscribe(); + if (this.altPhoneSubscription) this.altPhoneSubscription.unsubscribe(); + if (this.emailSubscription) this.emailSubscription.unsubscribe(); + if (this.confirmEmailSubscription) this.confirmEmailSubscription.unsubscribe(); + } + + preferredMethodOfContactChange(value) { + let phoneControl = this.form.get('phoneNumber'); + let altPhoneControl = this.form.get('alternatePhoneNumber'); + let emailControl = this.form.get('email'); + let emailConfirmControl = this.form.get('confirmEmail'); + let agreeToCVAPEmailControl = this.form.get('agreeToCvapCommunicationExchange'); + + this.addressHelper.clearAddressValidatorsAndErrors(this.form, 'primaryAddress'); + this.addressHelper.clearAddressValidatorsAndErrors(this.form, 'alternateAddress'); + this.addressHelper.setAddressAsRequired(this.form, 'primaryAddress'); + // this.addressHelper.markAsTouched(this.form, 'primaryAddress'); + + this.setControlValidators(phoneControl, [ + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + this.setControlValidators(emailControl, [Validators.email]); + this.setControlValidators(emailConfirmControl, [Validators.email, EmailValidator('email')]); + this.clearControlValidators(agreeToCVAPEmailControl); + + let contactMethod = parseInt(value); + if (contactMethod == 2) { + //phone call + this.setControlValidators(phoneControl, [ + Validators.required, + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + this.phoneIsRequired = true; + this.emailIsRequired = false; + this.addressIsRequired = false; + } else if (contactMethod == 1) { + //Email + this.setControlValidators(emailControl, [Validators.required, Validators.email]); + this.setControlValidators(emailConfirmControl, [Validators.required, Validators.email, EmailValidator('email')]); + this.setControlValidators(agreeToCVAPEmailControl, [Validators.requiredTrue]); + this.phoneIsRequired = false; + this.emailIsRequired = true; + this.addressIsRequired = false; + } else if (contactMethod == 4) { + //Mail + this.phoneIsRequired = false; + this.emailIsRequired = false; + this.addressIsRequired = true; + this.alternateAddressIsRequired = false; + } + + let voicemailOption = parseInt(this.form.get('leaveVoicemail').value); + if (voicemailOption == 100000000) { + //Primary and Alternate + this.setControlValidators(phoneControl, [ + Validators.required, + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + this.setControlValidators(altPhoneControl, [ + Validators.required, + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + } else if (voicemailOption == 100000001) { + //Primary only + this.setControlValidators(phoneControl, [ + Validators.required, + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + } else if (voicemailOption == 100000002) { + //Alternate only + this.setControlValidators(altPhoneControl, [ + Validators.required, + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + } - otherFirstNameControl.patchValue(''); - otherLastNameControl.patchValue(''); - dateOfNameChangeControl.patchValue(''); - } + if (agreeToCVAPEmailControl.value == true) { + this.setControlValidators(emailControl, [Validators.required, Validators.email]); + this.setControlValidators(emailConfirmControl, [Validators.required, Validators.email, EmailValidator('email')]); } - setPhoneValidators() { - if (this.form.get('primaryAddress.country').value == 'Canada' || this.form.get('primaryAddress.country').value == 'United States of America') { - this.phoneMinLength = 10; - } - else { - this.phoneMinLength = 8; - } - - // let contactMethod = this.form.get('preferredMethodOfContact').value; - let phoneControl = this.form.get('phoneNumber'); - let altPhoneControl = this.form.get('alternatePhoneNumber'); - //setup phone control validators based on preferredMethodOfContact - this.setControlValidators(phoneControl, [Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - this.setControlValidators(altPhoneControl, [Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - let contactMethod = this.form.get('preferredMethodOfContact').value; - if (contactMethod == 2) { //phone call - this.setControlValidators(phoneControl, [Validators.required, Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - } - //then update potentially update it based on voicemail selection - let voicemailVal = this.form.get('leaveVoicemail').value; - let voicemailOption = parseInt(voicemailVal); - if (voicemailOption == 100000000) { //Primary and Alternate - this.setControlValidators(phoneControl, [Validators.required, Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - this.setControlValidators(altPhoneControl, [Validators.required, Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - } - else if (voicemailOption == 100000001) { //Primary only - this.setControlValidators(phoneControl, [Validators.required, Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - } - else if (voicemailOption == 100000002) { //Alternate only - this.setControlValidators(altPhoneControl, [Validators.required, Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - } - - phoneControl.patchValue(phoneControl.value); - altPhoneControl.patchValue(altPhoneControl.value); + //verify that email is marked as required per "Other" address rule + this.setEmailValidators(); + } + + iHaveOtherNamesChange(val: boolean) { + if (!val) { + let otherFirstNameControl = this.form.get('otherFirstName'); + let otherLastNameControl = this.form.get('otherLastName'); + let dateOfNameChangeControl = this.form.get('dateOfNameChange'); + + otherFirstNameControl.patchValue(''); + otherLastNameControl.patchValue(''); + dateOfNameChangeControl.patchValue(''); } + } - setVoicemailValidators() { - let phoneVal = this.form.get('phoneNumber').value; - let altPhoneVal = this.form.get('alternatePhoneNumber').value; - let voicemailControl = this.form.get('leaveVoicemail'); - let options = { onlySelf: true, emitEvent: false }; - if (phoneVal || altPhoneVal) { - this.isVoiceMailRequired = true; - this.setControlValidators(voicemailControl, [Validators.required, Validators.min(1), Validators.max(100000003)], options); - } - else { - this.isVoiceMailRequired = false; - this.clearControlValidators(voicemailControl, options); - } + setPhoneValidators() { + if ( + this.form.get('primaryAddress.country').value == 'Canada' || + this.form.get('primaryAddress.country').value == 'United States of America' + ) { + this.phoneMinLength = 10; + } else { + this.phoneMinLength = 8; } - setEmailValidators() { - //email was already required - so we don't need to do anything right now - if (this.emailIsRequired) { - return; - } - let address = this.form.get('primaryAddress'); - let emailControl = this.form.get('email'); - this.setControlValidators(emailControl, [Validators.email]); + // let contactMethod = this.form.get('preferredMethodOfContact').value; + let phoneControl = this.form.get('phoneNumber'); + let altPhoneControl = this.form.get('alternatePhoneNumber'); + //setup phone control validators based on preferredMethodOfContact + this.setControlValidators(phoneControl, [ + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + this.setControlValidators(altPhoneControl, [ + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + let contactMethod = this.form.get('preferredMethodOfContact').value; + if (contactMethod == 2) { + //phone call + this.setControlValidators(phoneControl, [ + Validators.required, + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + } + //then update potentially update it based on voicemail selection + let voicemailVal = this.form.get('leaveVoicemail').value; + let voicemailOption = parseInt(voicemailVal); + if (voicemailOption == 100000000) { + //Primary and Alternate + this.setControlValidators(phoneControl, [ + Validators.required, + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + this.setControlValidators(altPhoneControl, [ + Validators.required, + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + } else if (voicemailOption == 100000001) { + //Primary only + this.setControlValidators(phoneControl, [ + Validators.required, + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + } else if (voicemailOption == 100000002) { + //Alternate only + this.setControlValidators(altPhoneControl, [ + Validators.required, + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); } - doNotLiveAtAddressChange(val: boolean) { - if (!val) { - this.form.get('mailRecipient').patchValue(''); - } + phoneControl.patchValue(phoneControl.value); + altPhoneControl.patchValue(altPhoneControl.value); + } + + setVoicemailValidators() { + let phoneVal = this.form.get('phoneNumber').value; + let altPhoneVal = this.form.get('alternatePhoneNumber').value; + let voicemailControl = this.form.get('leaveVoicemail'); + let options = { onlySelf: true, emitEvent: false }; + if (phoneVal || altPhoneVal) { + this.isVoiceMailRequired = true; + this.setControlValidators( + voicemailControl, + [Validators.required, Validators.min(1), Validators.max(100000003)], + options + ); + } else { + this.isVoiceMailRequired = false; + this.clearControlValidators(voicemailControl, options); } + } - canEmailChange(val: boolean) { - this.preferredMethodOfContactChange(this.form.get('preferredMethodOfContact').value); + setEmailValidators() { + //email was already required - so we don't need to do anything right now + if (this.emailIsRequired) { + return; + } + let address = this.form.get('primaryAddress'); + let emailControl = this.form.get('email'); + this.setControlValidators(emailControl, [Validators.email]); + } + + doNotLiveAtAddressChange(val: boolean) { + if (!val) { + this.form.get('mailRecipient').patchValue(''); } -} \ No newline at end of file + } + + canEmailChange(val: boolean) { + this.preferredMethodOfContactChange(this.form.get('preferredMethodOfContact').value); + } +} diff --git a/vsd-app/ClientApp/src/app/shared/personal-information/personal-information.helper.ts b/vsd-app/ClientApp/src/app/shared/personal-information/personal-information.helper.ts index 891eb2a9..b5ae0272 100644 --- a/vsd-app/ClientApp/src/app/shared/personal-information/personal-information.helper.ts +++ b/vsd-app/ClientApp/src/app/shared/personal-information/personal-information.helper.ts @@ -1,76 +1,73 @@ -import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms"; -import { ApplicationType } from "../enums-list"; -import { POSTAL_CODE } from "../regex.constants"; -import { EmailValidator } from "../validators/email.validator"; +import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms'; +import { ApplicationType } from '../enums-list'; +import { POSTAL_CODE } from '../regex.constants'; +import { EmailValidator } from '../validators/email.validator'; export class PersonalInfoHelper { - postalRegex = POSTAL_CODE; - public setupFormGroup(fb: FormBuilder, form_type: ApplicationType): FormGroup { - let group = { - firstName: ['', Validators.required], - middleName: [''], - lastName: ['', Validators.required], + postalRegex = POSTAL_CODE; + public setupFormGroup(fb: FormBuilder, form_type: ApplicationType): FormGroup { + let group = { + firstName: ['', Validators.required], + middleName: [''], + lastName: ['', Validators.required], - iHaveOtherNames: [''], - otherFirstName: [''], - otherLastName: [''], - dateOfNameChange: [''], + iHaveOtherNames: [''], + otherFirstName: [''], + otherLastName: [''], + dateOfNameChange: [''], - gender: [null], - birthDate: ['', [Validators.required]], - sin: ['', [Validators.minLength(9), Validators.maxLength(9)]], - occupation: [''], - indigenousStatus: [0, [Validators.required, Validators.min(100000000), Validators.max(100000004)]], + gender: [null], + birthDate: ['', [Validators.required]], + sin: ['', [Validators.minLength(9), Validators.maxLength(9)]], + occupation: [''], + indigenousStatus: [0, [Validators.required, Validators.min(100000000), Validators.max(100000004)]], - preferredMethodOfContact: [0, [Validators.required, Validators.min(1), Validators.max(100000002)]], // Phone = 2, Email = 1, Mail = 4, Alternate Mail = 100000002 + preferredMethodOfContact: [0, [Validators.required, Validators.min(1), Validators.max(100000002)]], // Phone = 2, Email = 1, Mail = 4, Alternate Mail = 100000002 - permissionToContactViaMethod: [false], - agreeToCvapCommunicationExchange: [''], + permissionToContactViaMethod: [false], + agreeToCvapCommunicationExchange: [''], - phoneNumber: ['', [Validators.minLength(10), Validators.maxLength(15)]], - leaveVoicemail: [0], - alternatePhoneNumber: [''], + phoneNumber: ['', [Validators.minLength(10), Validators.maxLength(15)]], + leaveVoicemail: [0], + alternatePhoneNumber: [''], - email: ['', [Validators.email]], - confirmEmail: ['', [ - Validators.email, - EmailValidator('email') - ]], + email: ['', [Validators.email]], + confirmEmail: ['', [Validators.email, EmailValidator('email')]], - doNotLiveAtAddress: [false], - mailRecipient: [''], - primaryAddress: fb.group({ - line1: ['', [Validators.required]], - line2: [''], - city: ['', [Validators.required]], - postalCode: ['', [Validators.required, Validators.pattern(this.postalRegex)]], - province: [{ value: 'British Columbia', disabled: false }, [Validators.required]], - country: [{ value: 'Canada', disabled: false }, [Validators.required]], - }), - alternateAddress: fb.group({ - line1: [''], - line2: [''], - city: [''], - postalCode: ['', [Validators.pattern(this.postalRegex)]], - province: [{ value: 'British Columbia', disabled: false }], - country: [{ value: 'Canada', disabled: false }], - }), - } + doNotLiveAtAddress: [false], + mailRecipient: [''], + primaryAddress: fb.group({ + line1: ['', [Validators.required]], + line2: [''], + city: ['', [Validators.required]], + postalCode: ['', [Validators.required, Validators.pattern(this.postalRegex)]], + province: [{ value: 'British Columbia', disabled: false }, [Validators.required]], + country: [{ value: 'Canada', disabled: false }, [Validators.required]] + }), + alternateAddress: fb.group({ + line1: [''], + line2: [''], + city: [''], + postalCode: ['', [Validators.pattern(this.postalRegex)]], + province: [{ value: 'British Columbia', disabled: false }], + country: [{ value: 'Canada', disabled: false }] + }) + }; - if (form_type === ApplicationType.IFM_Application) { - group['relationshipToVictim'] = ['', [Validators.required]]; - group['relationshipToVictimOther'] = ['']; - } - - if (form_type === ApplicationType.Witness_Application) { - group['relationshipToVictim'] = ['Other']; - group['relationshipToVictimOther'] = ['', [Validators.required]]; - } + if (form_type === ApplicationType.IFM_Application) { + group['relationshipToVictim'] = ['', [Validators.required]]; + group['relationshipToVictimOther'] = ['']; + } - if (form_type === ApplicationType.Victim_Application) { - group['maritalStatus'] = [0, [Validators.required, Validators.min(100000000), Validators.max(100000006)]]; - } + if (form_type === ApplicationType.Witness_Application) { + group['relationshipToVictim'] = ['Other']; + group['relationshipToVictimOther'] = ['', [Validators.required]]; + } - return fb.group(group); + if (form_type === ApplicationType.Victim_Application) { + group['maritalStatus'] = [0, [Validators.required, Validators.min(100000000), Validators.max(100000006)]]; } -} \ No newline at end of file + + return fb.group(group); + } +} diff --git a/vsd-app/ClientApp/src/app/shared/regex.constants.ts b/vsd-app/ClientApp/src/app/shared/regex.constants.ts index 1c153cc1..af0bdc08 100644 --- a/vsd-app/ClientApp/src/app/shared/regex.constants.ts +++ b/vsd-app/ClientApp/src/app/shared/regex.constants.ts @@ -1,2 +1,2 @@ export const POSTAL_CODE: RegExp = /^[A-Za-z][0-9][A-Za-z][ ]?[0-9][A-Za-z][0-9] *$/; -export const ZIP_CODE: RegExp = /^\d{5}(?:\d{2})?$/; \ No newline at end of file +export const ZIP_CODE: RegExp = /^\d{5}(?:\d{2})?$/; diff --git a/vsd-app/ClientApp/src/app/shared/representative-information/representative-information.component.scss b/vsd-app/ClientApp/src/app/shared/representative-information/representative-information.component.scss index b007377e..c7d3b7ce 100644 --- a/vsd-app/ClientApp/src/app/shared/representative-information/representative-information.component.scss +++ b/vsd-app/ClientApp/src/app/shared/representative-information/representative-information.component.scss @@ -40,4 +40,4 @@ input.form-control { &.bigger { width: 75%; } -} \ No newline at end of file +} diff --git a/vsd-app/ClientApp/src/app/shared/representative-information/representative-information.component.ts b/vsd-app/ClientApp/src/app/shared/representative-information/representative-information.component.ts index 71d442c7..987f7e4a 100644 --- a/vsd-app/ClientApp/src/app/shared/representative-information/representative-information.component.ts +++ b/vsd-app/ClientApp/src/app/shared/representative-information/representative-information.component.ts @@ -1,244 +1,259 @@ -import { OnInit, Component, Input, OnDestroy } from "@angular/core"; -import { FormBase } from "../form-base"; -import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS } from "@angular/material"; -import { FormGroup, Validators, FormBuilder, ControlContainer } from "@angular/forms"; -import { MomentDateAdapter } from "@angular/material-moment-adapter"; -import { MY_FORMATS, ApplicationType } from "../enums-list"; -import { COUNTRIES_ADDRESS } from "../address/country-list"; -import { AddressHelper } from "../address/address.helper"; -import { EmailValidator } from "../validators/email.validator"; -import { RepresentativeInfoHelper } from "./representative-information.helper"; -import { ActivatedRoute } from "@angular/router"; -import { Subscription } from "rxjs"; -import { iLookupData } from "../../interfaces/lookup-data.interface"; -import { LookupService } from "../../services/lookup.service"; +import { OnInit, Component, Input, OnDestroy } from '@angular/core'; +import { FormBase } from '../form-base'; +import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS } from '@angular/material'; +import { FormGroup, Validators, FormBuilder, ControlContainer } from '@angular/forms'; +import { MomentDateAdapter } from '@angular/material-moment-adapter'; +import { MY_FORMATS, ApplicationType } from '../enums-list'; +import { COUNTRIES_ADDRESS } from '../address/country-list'; +import { AddressHelper } from '../address/address.helper'; +import { EmailValidator } from '../validators/email.validator'; +import { RepresentativeInfoHelper } from './representative-information.helper'; +import { ActivatedRoute } from '@angular/router'; +import { Subscription } from 'rxjs'; +import { iLookupData } from '../../interfaces/lookup-data.interface'; +import { LookupService } from '../../services/lookup.service'; @Component({ - selector: 'app-representative-information', - templateUrl: './representative-information.component.html', - styleUrls: ['./representative-information.component.scss'], - providers: [ - // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your - // application's root module. We provide it at the component level here, due to limitations of - // our example generation script. - { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, - { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }, - ], + selector: 'app-representative-information', + templateUrl: './representative-information.component.html', + styleUrls: ['./representative-information.component.scss'], + providers: [ + // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your + // application's root module. We provide it at the component level here, due to limitations of + // our example generation script. + { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, + { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS } + ] }) export class RepresentativeInformationComponent extends FormBase implements OnInit, OnDestroy { - @Input() formType: number; - @Input() lookupData: iLookupData; - public form: FormGroup; - ApplicationType = ApplicationType; - provinceList: string[]; - relationshipList: string[]; - imfRelationshipList: string[]; - header: string; - - originalOnBehalfOf: number; - - representativeInfoHelper = new RepresentativeInfoHelper(); - - representativePhoneIsRequired: boolean = false; - representativeEmailIsRequired: boolean = false; - representativeAddressIsRequired: boolean = false; - - addressHelper = new AddressHelper(); - addressInfoSubscription: Subscription; - contactInfoSubscription: Subscription; - completingOnBehalfOfSubscription: Subscription; - methodOfContactSubscription: Subscription; - - constructor( - private controlContainer: ControlContainer, - private fb: FormBuilder, - private route: ActivatedRoute, - public lookupService: LookupService, - ) { - super(); - var canada = COUNTRIES_ADDRESS.filter(c => c.name.toLowerCase() == 'canada')[0]; - this.provinceList = canada.areas; - } + @Input() formType: number; + @Input() lookupData: iLookupData; + public form: FormGroup; + ApplicationType = ApplicationType; + provinceList: string[]; + relationshipList: string[]; + imfRelationshipList: string[]; + header: string; - ngOnInit() { - this.form = this.controlContainer.control; - setTimeout(() => { - this.form.markAsTouched(); - this.setRequiredFields(this.form.get('completingOnBehalfOf').value); - }, 0); - // console.log("representative info component"); - // console.log(this.form); - - if (this.formType === ApplicationType.Victim_Application) { - this.header = "Victim"; - } - if (this.formType === ApplicationType.IFM_Application) { - this.header = "Immediate Family Member"; - } - if (this.formType === ApplicationType.Witness_Application) { - this.header = "Witness"; - } + originalOnBehalfOf: number; - this.originalOnBehalfOf = parseInt(this.route.snapshot.queryParamMap.get('ob')); + representativeInfoHelper = new RepresentativeInfoHelper(); - this.completingOnBehalfOfSubscription = this.form.get('completingOnBehalfOf').valueChanges.subscribe(value => { - let relationshipToPersonControl = this.form.get('relationshipToPerson'); - relationshipToPersonControl.patchValue(''); - this.setRequiredFields(value); - }); + representativePhoneIsRequired: boolean = false; + representativeEmailIsRequired: boolean = false; + representativeAddressIsRequired: boolean = false; - this.methodOfContactSubscription = this.form.get('representativePreferredMethodOfContact').valueChanges.subscribe(value => { - let contactMethod = parseInt(value); - let completingOnBehalfOf = this.form.get('completingOnBehalfOf').value; - if (completingOnBehalfOf === 100000002 || completingOnBehalfOf === 100000003) { - this.setupRepresentativeContactInformation(contactMethod); - } - }); + addressHelper = new AddressHelper(); + addressInfoSubscription: Subscription; + contactInfoSubscription: Subscription; + completingOnBehalfOfSubscription: Subscription; + methodOfContactSubscription: Subscription; - this.addressInfoSubscription = this.form.get('mostRecentMailingAddressSameAsPersonal').valueChanges.subscribe(value => { - this.copyPersonalAddressToRepresentativeAddress(this.form.parent); - }); + constructor( + private controlContainer: ControlContainer, + private fb: FormBuilder, + private route: ActivatedRoute, + public lookupService: LookupService + ) { + super(); + var canada = COUNTRIES_ADDRESS.filter((c) => c.name.toLowerCase() == 'canada')[0]; + this.provinceList = canada.areas; + } - this.contactInfoSubscription = this.form.get('applicantSameContactInfo').valueChanges.subscribe(value => { - this.copyPersonalContactInfoToRepresentative(this.form.parent); - }); + ngOnInit() { + this.form = this.controlContainer.control; + setTimeout(() => { + this.form.markAsTouched(); + this.setRequiredFields(this.form.get('completingOnBehalfOf').value); + }, 0); + // console.log("representative info component"); + // console.log(this.form); - if (this.lookupData.imfRepresentativeRelationships && this.lookupData.imfRepresentativeRelationships.length > 0) { - this.imfRelationshipList = this.lookupData.imfRepresentativeRelationships.map(r => r.vsd_name); - } - else { - this.lookupService.getIMFRepresentativeRelationships().subscribe((res) => { - this.lookupData.imfRepresentativeRelationships = res.value; - if (this.lookupData.imfRepresentativeRelationships) { - this.lookupData.imfRepresentativeRelationships.sort(function (a, b) { - return a.vsd_name.localeCompare(b.vsd_name); - }); - } - this.imfRelationshipList = this.lookupData.imfRepresentativeRelationships.map(r => r.vsd_name); - }); - } + if (this.formType === ApplicationType.Victim_Application) { + this.header = 'Victim'; + } + if (this.formType === ApplicationType.IFM_Application) { + this.header = 'Immediate Family Member'; + } + if (this.formType === ApplicationType.Witness_Application) { + this.header = 'Witness'; + } + + this.originalOnBehalfOf = parseInt(this.route.snapshot.queryParamMap.get('ob')); + + this.completingOnBehalfOfSubscription = this.form.get('completingOnBehalfOf').valueChanges.subscribe((value) => { + let relationshipToPersonControl = this.form.get('relationshipToPerson'); + relationshipToPersonControl.patchValue(''); + this.setRequiredFields(value); + }); - if (this.lookupData.representativeRelationships && this.lookupData.representativeRelationships.length > 0) { - this.relationshipList = this.lookupData.representativeRelationships.map(r => r.vsd_name); + this.methodOfContactSubscription = this.form + .get('representativePreferredMethodOfContact') + .valueChanges.subscribe((value) => { + let contactMethod = parseInt(value); + let completingOnBehalfOf = this.form.get('completingOnBehalfOf').value; + if (completingOnBehalfOf === 100000002 || completingOnBehalfOf === 100000003) { + this.setupRepresentativeContactInformation(contactMethod); } - else { - this.lookupService.getRepresentativeRelationships().subscribe((res) => { - this.lookupData.representativeRelationships = res.value; - if (this.lookupData.representativeRelationships) { - this.lookupData.representativeRelationships.sort(function (a, b) { - return a.vsd_name.localeCompare(b.vsd_name); - }); - } - this.relationshipList = this.lookupData.representativeRelationships.map(r => r.vsd_name); - }); + }); + + this.addressInfoSubscription = this.form + .get('mostRecentMailingAddressSameAsPersonal') + .valueChanges.subscribe((value) => { + this.copyPersonalAddressToRepresentativeAddress(this.form.parent); + }); + + this.contactInfoSubscription = this.form.get('applicantSameContactInfo').valueChanges.subscribe((value) => { + this.copyPersonalContactInfoToRepresentative(this.form.parent); + }); + + if (this.lookupData.imfRepresentativeRelationships && this.lookupData.imfRepresentativeRelationships.length > 0) { + this.imfRelationshipList = this.lookupData.imfRepresentativeRelationships.map((r) => r.vsd_name); + } else { + this.lookupService.getIMFRepresentativeRelationships().subscribe((res) => { + this.lookupData.imfRepresentativeRelationships = res.value; + if (this.lookupData.imfRepresentativeRelationships) { + this.lookupData.imfRepresentativeRelationships.sort(function (a, b) { + return a.vsd_name.localeCompare(b.vsd_name); + }); } + this.imfRelationshipList = this.lookupData.imfRepresentativeRelationships.map((r) => r.vsd_name); + }); } - ngOnDestroy() { - if (this.completingOnBehalfOfSubscription) this.completingOnBehalfOfSubscription.unsubscribe(); - if (this.methodOfContactSubscription) this.methodOfContactSubscription.unsubscribe(); - if (this.contactInfoSubscription) this.contactInfoSubscription.unsubscribe(); - if (this.contactInfoSubscription) this.contactInfoSubscription.unsubscribe(); + if (this.lookupData.representativeRelationships && this.lookupData.representativeRelationships.length > 0) { + this.relationshipList = this.lookupData.representativeRelationships.map((r) => r.vsd_name); + } else { + this.lookupService.getRepresentativeRelationships().subscribe((res) => { + this.lookupData.representativeRelationships = res.value; + if (this.lookupData.representativeRelationships) { + this.lookupData.representativeRelationships.sort(function (a, b) { + return a.vsd_name.localeCompare(b.vsd_name); + }); + } + this.relationshipList = this.lookupData.representativeRelationships.map((r) => r.vsd_name); + }); } + } - setRequiredFields(completingOnBehalfOf: number) { - let representativeFirstName = this.form.get('representativeFirstName'); - let representativeLastName = this.form.get('representativeLastName'); - let applicantSameContactInfo = this.form.get('applicantSameContactInfo'); - let mostRecentMailingAddressSameAsPersonal = this.form.get('mostRecentMailingAddressSameAsPersonal'); - let representativePreferredMethodOfContact = this.form.get('representativePreferredMethodOfContact'); - - this.clearControlValidators(representativeFirstName); - this.clearControlValidators(representativeLastName); - this.clearControlValidators(applicantSameContactInfo); - this.clearControlValidators(mostRecentMailingAddressSameAsPersonal); - this.clearControlValidators(representativePreferredMethodOfContact); - this.addressHelper.clearAddressValidatorsAndErrors(this.form, 'representativeAddress'); - - let relationshipToPersonControl = this.form.get('relationshipToPerson'); - if (completingOnBehalfOf === 100000003) { //legal rep, fill in relationshipToPerson - this.setControlValidators(relationshipToPersonControl, [Validators.required]); - } - else if (completingOnBehalfOf === 100000002) { - relationshipToPersonControl.patchValue('Parent'); - this.clearControlValidators(relationshipToPersonControl); - } - else { - this.clearControlValidators(relationshipToPersonControl); - } + ngOnDestroy() { + if (this.completingOnBehalfOfSubscription) this.completingOnBehalfOfSubscription.unsubscribe(); + if (this.methodOfContactSubscription) this.methodOfContactSubscription.unsubscribe(); + if (this.contactInfoSubscription) this.contactInfoSubscription.unsubscribe(); + if (this.contactInfoSubscription) this.contactInfoSubscription.unsubscribe(); + } - let useValidation = completingOnBehalfOf === 100000002 || completingOnBehalfOf === 100000003; - if (useValidation) { - this.setupRepresentativeContactInformation(this.form.get('representativePreferredMethodOfContact').value); // Have to clear contact validators on contact method change - this.setControlValidators(representativeFirstName, [Validators.required]); - this.setControlValidators(representativeLastName, [Validators.required]); - this.setControlValidators(applicantSameContactInfo, [Validators.required]); - this.setControlValidators(mostRecentMailingAddressSameAsPersonal, [Validators.required]); - this.setControlValidators(representativePreferredMethodOfContact, [Validators.required, Validators.min(100000000), Validators.max(100000002)]); - } - else { - let options = { onlySelf: true, emitEvent: false }; - let freshForm = this.representativeInfoHelper.setupFormGroup(this.fb, this.formType); - freshForm.removeControl('completingOnBehalfOf'); - this.form.patchValue(freshForm.value, options); - } + setRequiredFields(completingOnBehalfOf: number) { + let representativeFirstName = this.form.get('representativeFirstName'); + let representativeLastName = this.form.get('representativeLastName'); + let applicantSameContactInfo = this.form.get('applicantSameContactInfo'); + let mostRecentMailingAddressSameAsPersonal = this.form.get('mostRecentMailingAddressSameAsPersonal'); + let representativePreferredMethodOfContact = this.form.get('representativePreferredMethodOfContact'); + + this.clearControlValidators(representativeFirstName); + this.clearControlValidators(representativeLastName); + this.clearControlValidators(applicantSameContactInfo); + this.clearControlValidators(mostRecentMailingAddressSameAsPersonal); + this.clearControlValidators(representativePreferredMethodOfContact); + this.addressHelper.clearAddressValidatorsAndErrors(this.form, 'representativeAddress'); + + let relationshipToPersonControl = this.form.get('relationshipToPerson'); + if (completingOnBehalfOf === 100000003) { + //legal rep, fill in relationshipToPerson + this.setControlValidators(relationshipToPersonControl, [Validators.required]); + } else if (completingOnBehalfOf === 100000002) { + relationshipToPersonControl.patchValue('Parent'); + this.clearControlValidators(relationshipToPersonControl); + } else { + this.clearControlValidators(relationshipToPersonControl); } - setupRepresentativeContactInformation(contactMethod: number): void { - let options = { onlySelf: true, emitEvent: false }; - let phoneControl = this.form.get('representativePhoneNumber'); - let emailControl = this.form.get('representativeEmail'); - let emailConfirmControl = this.form.get('representativeConfirmEmail'); - - this.addressHelper.clearAddressValidatorsAndErrors(this.form, 'representativeAddress'); - this.addressHelper.setAddressAsRequired(this.form, 'representativeAddress'); - - phoneControl.setValidators([Validators.minLength(8), Validators.maxLength(15)]); - phoneControl.setErrors(null, options); - emailControl.setValidators([Validators.email]); - emailControl.setErrors(null, options); - emailConfirmControl.setValidators([Validators.email, EmailValidator('representativeEmail')]); - emailConfirmControl.setErrors(null, options); - - if (contactMethod === 100000001) { //Phone Call - phoneControl.setValidators([Validators.required, Validators.minLength(8), Validators.maxLength(15)]); - this.representativePhoneIsRequired = true; - this.representativeEmailIsRequired = false; - } else if (contactMethod === 100000000) { //Email - emailControl.setValidators([Validators.required, Validators.email]); - emailConfirmControl.setValidators([Validators.required, Validators.email, EmailValidator('representativeEmail')]); - this.representativePhoneIsRequired = false; - this.representativeEmailIsRequired = true; - } else if (contactMethod === 100000002) { //Mail - this.representativePhoneIsRequired = false; - this.representativeEmailIsRequired = false; - } + let useValidation = completingOnBehalfOf === 100000002 || completingOnBehalfOf === 100000003; + if (useValidation) { + this.setupRepresentativeContactInformation(this.form.get('representativePreferredMethodOfContact').value); // Have to clear contact validators on contact method change + this.setControlValidators(representativeFirstName, [Validators.required]); + this.setControlValidators(representativeLastName, [Validators.required]); + this.setControlValidators(applicantSameContactInfo, [Validators.required]); + this.setControlValidators(mostRecentMailingAddressSameAsPersonal, [Validators.required]); + this.setControlValidators(representativePreferredMethodOfContact, [ + Validators.required, + Validators.min(100000000), + Validators.max(100000002) + ]); + } else { + let options = { onlySelf: true, emitEvent: false }; + let freshForm = this.representativeInfoHelper.setupFormGroup(this.fb, this.formType); + freshForm.removeControl('completingOnBehalfOf'); + this.form.patchValue(freshForm.value, options); + } + } + + setupRepresentativeContactInformation(contactMethod: number): void { + let options = { onlySelf: true, emitEvent: false }; + let phoneControl = this.form.get('representativePhoneNumber'); + let emailControl = this.form.get('representativeEmail'); + let emailConfirmControl = this.form.get('representativeConfirmEmail'); - this.representativeAddressIsRequired = true; + this.addressHelper.clearAddressValidatorsAndErrors(this.form, 'representativeAddress'); + this.addressHelper.setAddressAsRequired(this.form, 'representativeAddress'); - phoneControl.markAsTouched(); - phoneControl.updateValueAndValidity(options); - emailControl.markAsTouched(); - emailControl.updateValueAndValidity(options); - emailConfirmControl.markAsTouched(); - emailConfirmControl.updateValueAndValidity(options); + phoneControl.setValidators([Validators.minLength(8), Validators.maxLength(15)]); + phoneControl.setErrors(null, options); + emailControl.setValidators([Validators.email]); + emailControl.setErrors(null, options); + emailConfirmControl.setValidators([Validators.email, EmailValidator('representativeEmail')]); + emailConfirmControl.setErrors(null, options); + + if (contactMethod === 100000001) { + //Phone Call + phoneControl.setValidators([Validators.required, Validators.minLength(8), Validators.maxLength(15)]); + this.representativePhoneIsRequired = true; + this.representativeEmailIsRequired = false; + } else if (contactMethod === 100000000) { + //Email + emailControl.setValidators([Validators.required, Validators.email]); + emailConfirmControl.setValidators([Validators.required, Validators.email, EmailValidator('representativeEmail')]); + this.representativePhoneIsRequired = false; + this.representativeEmailIsRequired = true; + } else if (contactMethod === 100000002) { + //Mail + this.representativePhoneIsRequired = false; + this.representativeEmailIsRequired = false; } - setRepresentativePhoneValidators() { - let phoneMinLength = 10; - let phoneMaxLength = 15; - if (this.form.get('representativeAddress.country').value === 'Canada' || this.form.get('representativeAddress.country').value === 'United States of America') { - phoneMinLength = 10; - } - else { - phoneMinLength = 8; - } + this.representativeAddressIsRequired = true; + + phoneControl.markAsTouched(); + phoneControl.updateValueAndValidity(options); + emailControl.markAsTouched(); + emailControl.updateValueAndValidity(options); + emailConfirmControl.markAsTouched(); + emailConfirmControl.updateValueAndValidity(options); + } - let phoneControl = this.form.get('representativePhoneNumber'); - let altPhoneControl = this.form.get('representativeAlternatePhoneNumber'); - this.setControlValidators(phoneControl, [Validators.minLength(phoneMinLength), Validators.maxLength(phoneMaxLength)]); - this.setControlValidators(altPhoneControl, [Validators.minLength(phoneMinLength), Validators.maxLength(phoneMaxLength)]); - phoneControl.patchValue(phoneControl.value); - altPhoneControl.patchValue(altPhoneControl.value); + setRepresentativePhoneValidators() { + let phoneMinLength = 10; + let phoneMaxLength = 15; + if ( + this.form.get('representativeAddress.country').value === 'Canada' || + this.form.get('representativeAddress.country').value === 'United States of America' + ) { + phoneMinLength = 10; + } else { + phoneMinLength = 8; } -} \ No newline at end of file + + let phoneControl = this.form.get('representativePhoneNumber'); + let altPhoneControl = this.form.get('representativeAlternatePhoneNumber'); + this.setControlValidators(phoneControl, [ + Validators.minLength(phoneMinLength), + Validators.maxLength(phoneMaxLength) + ]); + this.setControlValidators(altPhoneControl, [ + Validators.minLength(phoneMinLength), + Validators.maxLength(phoneMaxLength) + ]); + phoneControl.patchValue(phoneControl.value); + altPhoneControl.patchValue(altPhoneControl.value); + } +} diff --git a/vsd-app/ClientApp/src/app/shared/representative-information/representative-information.helper.ts b/vsd-app/ClientApp/src/app/shared/representative-information/representative-information.helper.ts index 6d6a4ca6..c8eedfcc 100644 --- a/vsd-app/ClientApp/src/app/shared/representative-information/representative-information.helper.ts +++ b/vsd-app/ClientApp/src/app/shared/representative-information/representative-information.helper.ts @@ -1,46 +1,43 @@ -import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms"; -import { ApplicationType } from "../enums-list"; -import { POSTAL_CODE } from "../regex.constants"; -import { EmailValidator } from "../validators/email.validator"; +import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms'; +import { ApplicationType } from '../enums-list'; +import { POSTAL_CODE } from '../regex.constants'; +import { EmailValidator } from '../validators/email.validator'; export class RepresentativeInfoHelper { - postalRegex = POSTAL_CODE; - public setupFormGroup(fb: FormBuilder, form_type: ApplicationType): FormGroup { - let group = { - completingOnBehalfOf: [0, [Validators.required, Validators.min(100000000), Validators.max(100000003)]], // Self: 100000000 Victim Service Worker: 100000001 Parent/Guardian: 100000002, - representativeFirstName: [''], //, Validators.required], - representativeMiddleName: [''], - representativeLastName: [''], //, Validators.required], - representativePreferredMethodOfContact: [0], // Phone = 100000000, Email = 100000001, Mail = 100000002 - representativePhoneNumber: [''], - representativeAlternatePhoneNumber: [''], + postalRegex = POSTAL_CODE; + public setupFormGroup(fb: FormBuilder, form_type: ApplicationType): FormGroup { + let group = { + completingOnBehalfOf: [0, [Validators.required, Validators.min(100000000), Validators.max(100000003)]], // Self: 100000000 Victim Service Worker: 100000001 Parent/Guardian: 100000002, + representativeFirstName: [''], //, Validators.required], + representativeMiddleName: [''], + representativeLastName: [''], //, Validators.required], + representativePreferredMethodOfContact: [0], // Phone = 100000000, Email = 100000001, Mail = 100000002 + representativePhoneNumber: [''], + representativeAlternatePhoneNumber: [''], - // representativeEmail: [''], - // representativeConfirmEmail: [''], - representativeEmail: ['', [Validators.email]], //, [Validators.required, Validators.email]], - representativeConfirmEmail: ['', [ - Validators.email, - EmailValidator('representativeEmail') - ]], + // representativeEmail: [''], + // representativeConfirmEmail: [''], + representativeEmail: ['', [Validators.email]], //, [Validators.required, Validators.email]], + representativeConfirmEmail: ['', [Validators.email, EmailValidator('representativeEmail')]], - applicantSameContactInfo: [''], - mostRecentMailingAddressSameAsPersonal: [''], - representativeAddress: fb.group({ - line1: [''], - line2: [''], - city: [''], - postalCode: ['', [Validators.pattern(this.postalRegex)]], // , - province: [{ value: 'British Columbia', disabled: false }], - country: [{ value: 'Canada', disabled: false }], - }), - documents: fb.array([]), - relationshipToPerson: [''], - }; + applicantSameContactInfo: [''], + mostRecentMailingAddressSameAsPersonal: [''], + representativeAddress: fb.group({ + line1: [''], + line2: [''], + city: [''], + postalCode: ['', [Validators.pattern(this.postalRegex)]], // , + province: [{ value: 'British Columbia', disabled: false }], + country: [{ value: 'Canada', disabled: false }] + }), + documents: fb.array([]), + relationshipToPerson: [''] + }; - // if (form_type === ApplicationType.Victim_Application || form_type === ApplicationType.IFM_Application) { + // if (form_type === ApplicationType.Victim_Application || form_type === ApplicationType.IFM_Application) { - // } + // } - return fb.group(group); - } -} \ No newline at end of file + return fb.group(group); + } +} diff --git a/vsd-app/ClientApp/src/app/shared/tool-tip/tool-tip.component.ts b/vsd-app/ClientApp/src/app/shared/tool-tip/tool-tip.component.ts index f53faeeb..17d70281 100644 --- a/vsd-app/ClientApp/src/app/shared/tool-tip/tool-tip.component.ts +++ b/vsd-app/ClientApp/src/app/shared/tool-tip/tool-tip.component.ts @@ -7,9 +7,7 @@ import { Component, OnInit, Input } from '@angular/core'; export class ToolTipTriggerComponent implements OnInit { @Input() trigger = ''; - constructor() { } - - ngOnInit() { - } + constructor() {} + ngOnInit() {} } diff --git a/vsd-app/ClientApp/src/app/shared/validators/email.validator.ts b/vsd-app/ClientApp/src/app/shared/validators/email.validator.ts index f652840a..b02e05b1 100644 --- a/vsd-app/ClientApp/src/app/shared/validators/email.validator.ts +++ b/vsd-app/ClientApp/src/app/shared/validators/email.validator.ts @@ -17,14 +17,11 @@ export function EmailValidator(confirmEmailInput: string) { }); } - if ( - emailControl.value.toLocaleLowerCase() !== - confirmEmailControl.value.toLocaleLowerCase() - ) { + if (emailControl.value.toLocaleLowerCase() !== confirmEmailControl.value.toLocaleLowerCase()) { return { notMatch: true }; } return null; }; -} \ No newline at end of file +} diff --git a/vsd-app/ClientApp/src/app/shared/victim-information/victim-information.component.scss b/vsd-app/ClientApp/src/app/shared/victim-information/victim-information.component.scss index 355fe737..45423b4b 100644 --- a/vsd-app/ClientApp/src/app/shared/victim-information/victim-information.component.scss +++ b/vsd-app/ClientApp/src/app/shared/victim-information/victim-information.component.scss @@ -224,8 +224,8 @@ input.form-control { margin-bottom: 5px; } - input[type="checkbox"], - input[type="radio"] { + input[type='checkbox'], + input[type='radio'] { margin-right: 5px; } @@ -248,7 +248,7 @@ input.form-control { } ::ng-deep .terms { - input[type="text"] { + input[type='text'] { margin-left: 15px; } diff --git a/vsd-app/ClientApp/src/app/shared/victim-information/victim-information.component.ts b/vsd-app/ClientApp/src/app/shared/victim-information/victim-information.component.ts index 2472da12..2547244e 100644 --- a/vsd-app/ClientApp/src/app/shared/victim-information/victim-information.component.ts +++ b/vsd-app/ClientApp/src/app/shared/victim-information/victim-information.component.ts @@ -1,108 +1,116 @@ -import { OnInit, Component, Input, OnDestroy } from "@angular/core"; -import { FormBase } from "../form-base"; -import { MatDialog, DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS } from "@angular/material"; -import { FormGroup, FormBuilder, ControlContainer, AbstractControl, Validators } from "@angular/forms"; -import { MomentDateAdapter } from "@angular/material-moment-adapter"; -import { MY_FORMATS, ApplicationType } from "../enums-list"; -import { Subscription } from "rxjs"; -import { iLookupData } from "../../interfaces/lookup-data.interface"; +import { OnInit, Component, Input, OnDestroy } from '@angular/core'; +import { FormBase } from '../form-base'; +import { MatDialog, DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS } from '@angular/material'; +import { FormGroup, FormBuilder, ControlContainer, AbstractControl, Validators } from '@angular/forms'; +import { MomentDateAdapter } from '@angular/material-moment-adapter'; +import { MY_FORMATS, ApplicationType } from '../enums-list'; +import { Subscription } from 'rxjs'; +import { iLookupData } from '../../interfaces/lookup-data.interface'; @Component({ - selector: 'app-victim-information', - templateUrl: './victim-information.component.html', - styleUrls: ['./victim-information.component.scss'], - providers: [ - { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, - { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }, - ], + selector: 'app-victim-information', + templateUrl: './victim-information.component.html', + styleUrls: ['./victim-information.component.scss'], + providers: [ + { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, + { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS } + ] }) export class VictimInformationComponent extends FormBase implements OnInit, OnDestroy { - @Input() formType: number; - @Input() lookupData: iLookupData; - public form: FormGroup; - ApplicationType = ApplicationType; - todaysDate = new Date(); // for the birthdate validation - oldestHuman = new Date(this.todaysDate.getFullYear() - 120, this.todaysDate.getMonth(), this.todaysDate.getDay()); - phoneIsRequired: boolean = false; - emailIsRequired: boolean = false; - addressIsRequired: boolean = false; + @Input() formType: number; + @Input() lookupData: iLookupData; + public form: FormGroup; + ApplicationType = ApplicationType; + todaysDate = new Date(); // for the birthdate validation + oldestHuman = new Date(this.todaysDate.getFullYear() - 120, this.todaysDate.getMonth(), this.todaysDate.getDay()); + phoneIsRequired: boolean = false; + emailIsRequired: boolean = false; + addressIsRequired: boolean = false; - phoneMinLength: number = 10; - phoneMaxLength: number = 15; + phoneMinLength: number = 10; + phoneMaxLength: number = 15; - addressInfoSubscription: Subscription; - addressSubscription: Subscription; - contactInfoSubscription: Subscription; + addressInfoSubscription: Subscription; + addressSubscription: Subscription; + contactInfoSubscription: Subscription; - constructor( - private controlContainer: ControlContainer, - private matDialog: MatDialog, - private fb: FormBuilder, - ) { - super(); - } - - ngOnInit() { - this.form = this.controlContainer.control; - setTimeout(() => { this.form.markAsTouched(); }, 0); - // console.log("victim info component"); - // console.log(this.form); + constructor(private controlContainer: ControlContainer, private matDialog: MatDialog, private fb: FormBuilder) { + super(); + } - if (this.form.get('victimSameContactInfo').value === true) { - this.copyPersonalContactInfoToVictim(this.form.parent); - } + ngOnInit() { + this.form = this.controlContainer.control; + setTimeout(() => { + this.form.markAsTouched(); + }, 0); + // console.log("victim info component"); + // console.log(this.form); - if (this.form.get('mostRecentMailingAddressSameAsPersonal').value === true) { - this.copyPersonalAddressToVictimAddress(this.form.parent); - this.setPhoneValidators(); - } + if (this.form.get('victimSameContactInfo').value === true) { + this.copyPersonalContactInfoToVictim(this.form.parent); + } - if (this.formType === ApplicationType.IFM_Application || this.formType === ApplicationType.Witness_Application) { - this.addressInfoSubscription = this.form.get('mostRecentMailingAddressSameAsPersonal').valueChanges.subscribe(value => { - this.copyPersonalAddressToVictimAddress(this.form.parent); - this.setPhoneValidators(); - }); - this.contactInfoSubscription = this.form.get('victimSameContactInfo').valueChanges.subscribe(value => { - this.copyPersonalContactInfoToVictim(this.form.parent); - }); - } + if (this.form.get('mostRecentMailingAddressSameAsPersonal').value === true) { + this.copyPersonalAddressToVictimAddress(this.form.parent); + this.setPhoneValidators(); + } - this.addressSubscription = this.form.get('primaryAddress').valueChanges.subscribe(value => { - this.setPhoneValidators(); + if (this.formType === ApplicationType.IFM_Application || this.formType === ApplicationType.Witness_Application) { + this.addressInfoSubscription = this.form + .get('mostRecentMailingAddressSameAsPersonal') + .valueChanges.subscribe((value) => { + this.copyPersonalAddressToVictimAddress(this.form.parent); + this.setPhoneValidators(); }); + this.contactInfoSubscription = this.form.get('victimSameContactInfo').valueChanges.subscribe((value) => { + this.copyPersonalContactInfoToVictim(this.form.parent); + }); } - ngOnDestroy() { - if (this.addressInfoSubscription) this.addressInfoSubscription.unsubscribe(); - if (this.addressSubscription) this.addressSubscription.unsubscribe(); - if (this.contactInfoSubscription) this.contactInfoSubscription.unsubscribe(); - } + this.addressSubscription = this.form.get('primaryAddress').valueChanges.subscribe((value) => { + this.setPhoneValidators(); + }); + } - iHaveOtherNamesChange(val: boolean) { - if (!val) { - let otherFirstNameControl = this.form.get('otherFirstName'); - let otherLastNameControl = this.form.get('otherLastName'); - let dateOfNameChangeControl = this.form.get('dateOfNameChange'); + ngOnDestroy() { + if (this.addressInfoSubscription) this.addressInfoSubscription.unsubscribe(); + if (this.addressSubscription) this.addressSubscription.unsubscribe(); + if (this.contactInfoSubscription) this.contactInfoSubscription.unsubscribe(); + } - otherFirstNameControl.patchValue(''); - otherLastNameControl.patchValue(''); - dateOfNameChangeControl.patchValue(''); - } - } + iHaveOtherNamesChange(val: boolean) { + if (!val) { + let otherFirstNameControl = this.form.get('otherFirstName'); + let otherLastNameControl = this.form.get('otherLastName'); + let dateOfNameChangeControl = this.form.get('dateOfNameChange'); - setPhoneValidators() { - if (this.form.get('primaryAddress.country').value === 'Canada' || this.form.get('primaryAddress.country').value === 'United States of America') { - this.phoneMinLength = 10; - } - else { - this.phoneMinLength = 8; - } + otherFirstNameControl.patchValue(''); + otherLastNameControl.patchValue(''); + dateOfNameChangeControl.patchValue(''); + } + } - let phoneControl = this.form.get('phoneNumber'); - let altPhoneControl = this.form.get('alternatePhoneNumber'); - this.setControlValidators(phoneControl, [Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - this.setControlValidators(altPhoneControl, [Validators.minLength(this.phoneMinLength), Validators.maxLength(this.phoneMaxLength)]); - phoneControl.patchValue(phoneControl.value); - altPhoneControl.patchValue(altPhoneControl.value); + setPhoneValidators() { + if ( + this.form.get('primaryAddress.country').value === 'Canada' || + this.form.get('primaryAddress.country').value === 'United States of America' + ) { + this.phoneMinLength = 10; + } else { + this.phoneMinLength = 8; } -} \ No newline at end of file + + let phoneControl = this.form.get('phoneNumber'); + let altPhoneControl = this.form.get('alternatePhoneNumber'); + this.setControlValidators(phoneControl, [ + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + this.setControlValidators(altPhoneControl, [ + Validators.minLength(this.phoneMinLength), + Validators.maxLength(this.phoneMaxLength) + ]); + phoneControl.patchValue(phoneControl.value); + altPhoneControl.patchValue(altPhoneControl.value); + } +} diff --git a/vsd-app/ClientApp/src/app/shared/victim-information/victim-information.helper.ts b/vsd-app/ClientApp/src/app/shared/victim-information/victim-information.helper.ts index ca516cf2..c2f963d7 100644 --- a/vsd-app/ClientApp/src/app/shared/victim-information/victim-information.helper.ts +++ b/vsd-app/ClientApp/src/app/shared/victim-information/victim-information.helper.ts @@ -1,6 +1,6 @@ -import { FormBuilder, FormGroup, Validators } from "@angular/forms"; -import { POSTAL_CODE } from "../regex.constants"; -import { EmailValidator } from "../validators/email.validator"; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { POSTAL_CODE } from '../regex.constants'; +import { EmailValidator } from '../validators/email.validator'; /** * Helper class for setting up victim information form. @@ -18,41 +18,34 @@ export class VictimInfoHelper { */ public setupFormGroupForVictimApplication(fb: FormBuilder): FormGroup { let group = { - firstName: ["", Validators.required], - middleName: [""], - lastName: ["", Validators.required], + firstName: ['', Validators.required], + middleName: [''], + lastName: ['', Validators.required], - iHaveOtherNames: [""], - otherFirstName: [""], - otherLastName: [""], - dateOfNameChange: [""], + iHaveOtherNames: [''], + otherFirstName: [''], + otherLastName: [''], + dateOfNameChange: [''], gender: [null], - maritalStatus: [ - null, - [ - Validators.required, - Validators.min(100000000), - Validators.max(100000006), - ], - ], - - victimSameContactInfo: [""], - phoneNumber: [""], - alternatePhoneNumber: [""], - email: [""], - confirmEmail: ["", [Validators.email, EmailValidator("email")]], - - mostRecentMailingAddressSameAsPersonal: [""], + maritalStatus: [null, [Validators.required, Validators.min(100000000), Validators.max(100000006)]], + + victimSameContactInfo: [''], + phoneNumber: [''], + alternatePhoneNumber: [''], + email: [''], + confirmEmail: ['', [Validators.email, EmailValidator('email')]], + + mostRecentMailingAddressSameAsPersonal: [''], primaryAddress: fb.group({ - line1: [""], - line2: [""], - city: [""], - postalCode: ["", [Validators.pattern(POSTAL_CODE)]], - province: [{ value: "British Columbia", disabled: false }], - country: [{ value: "Canada", disabled: false }], - }), + line1: [''], + line2: [''], + city: [''], + postalCode: ['', [Validators.pattern(POSTAL_CODE)]], + province: [{ value: 'British Columbia', disabled: false }], + country: [{ value: 'Canada', disabled: false }] + }) }; return fb.group(group); @@ -67,36 +60,36 @@ export class VictimInfoHelper { */ public setupFormGroupForWitnessApplication(fb: FormBuilder): FormGroup { let group = { - firstName: [""], - middleName: [""], - lastName: [""], + firstName: [''], + middleName: [''], + lastName: [''], - iHaveOtherNames: [""], - otherFirstName: [""], - otherLastName: [""], - dateOfNameChange: [""], + iHaveOtherNames: [''], + otherFirstName: [''], + otherLastName: [''], + dateOfNameChange: [''], birthDate: [null], gender: [null], maritalStatus: [null], - victimSameContactInfo: [""], - phoneNumber: [""], - alternatePhoneNumber: [""], - email: [""], - confirmEmail: ["", [Validators.email, EmailValidator("email")]], + victimSameContactInfo: [''], + phoneNumber: [''], + alternatePhoneNumber: [''], + email: [''], + confirmEmail: ['', [Validators.email, EmailValidator('email')]], - mostRecentMailingAddressSameAsPersonal: [""], + mostRecentMailingAddressSameAsPersonal: [''], primaryAddress: fb.group({ - line1: [""], - line2: [""], - city: [""], - postalCode: ["", [Validators.pattern(POSTAL_CODE)]], - province: [{ value: "British Columbia", disabled: false }], - country: [{ value: "Canada", disabled: false }], - }), + line1: [''], + line2: [''], + city: [''], + postalCode: ['', [Validators.pattern(POSTAL_CODE)]], + province: [{ value: 'British Columbia', disabled: false }], + country: [{ value: 'Canada', disabled: false }] + }) }; return fb.group(group); @@ -111,45 +104,38 @@ export class VictimInfoHelper { */ public setupFormGroupForIfmApplication(fb: FormBuilder): FormGroup { let group = { - firstName: ["", Validators.required], - middleName: [""], - lastName: ["", Validators.required], + firstName: ['', Validators.required], + middleName: [''], + lastName: ['', Validators.required], - iHaveOtherNames: [""], - otherFirstName: [""], - otherLastName: [""], - dateOfNameChange: [""], + iHaveOtherNames: [''], + otherFirstName: [''], + otherLastName: [''], + dateOfNameChange: [''], - sin: ["", [Validators.minLength(9), Validators.maxLength(9)]], - occupation: [""], + sin: ['', [Validators.minLength(9), Validators.maxLength(9)]], + occupation: [''], birthDate: [null, [Validators.required]], gender: [null], - maritalStatus: [ - null, - [ - Validators.required, - Validators.min(100000000), - Validators.max(100000006), - ], - ], - - victimSameContactInfo: [""], - phoneNumber: [""], - alternatePhoneNumber: [""], - email: [""], - confirmEmail: ["", [Validators.email, EmailValidator("email")]], - - mostRecentMailingAddressSameAsPersonal: [""], + maritalStatus: [null, [Validators.required, Validators.min(100000000), Validators.max(100000006)]], + + victimSameContactInfo: [''], + phoneNumber: [''], + alternatePhoneNumber: [''], + email: [''], + confirmEmail: ['', [Validators.email, EmailValidator('email')]], + + mostRecentMailingAddressSameAsPersonal: [''], primaryAddress: fb.group({ - line1: [""], - line2: [""], - city: [""], - postalCode: ["", [Validators.pattern(POSTAL_CODE)]], - province: [{ value: "British Columbia", disabled: false }], - country: [{ value: "Canada", disabled: false }], - }), + line1: [''], + line2: [''], + city: [''], + postalCode: ['', [Validators.pattern(POSTAL_CODE)]], + province: [{ value: 'British Columbia', disabled: false }], + country: [{ value: 'Canada', disabled: false }] + }) }; return fb.group(group); diff --git a/vsd-app/ClientApp/src/app/sign-dialog/sign-dialog.component.spec.ts b/vsd-app/ClientApp/src/app/sign-dialog/sign-dialog.component.spec.ts index e6dd5ee9..4f014a4b 100644 --- a/vsd-app/ClientApp/src/app/sign-dialog/sign-dialog.component.spec.ts +++ b/vsd-app/ClientApp/src/app/sign-dialog/sign-dialog.component.spec.ts @@ -8,9 +8,8 @@ describe('SignPadDialog', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - declarations: [SignPadDialog ] - }) - .compileComponents(); + declarations: [SignPadDialog] + }).compileComponents(); })); beforeEach(() => { diff --git a/vsd-app/ClientApp/src/app/sign-dialog/sign-dialog.component.ts b/vsd-app/ClientApp/src/app/sign-dialog/sign-dialog.component.ts index d978db96..cb67e4b3 100644 --- a/vsd-app/ClientApp/src/app/sign-dialog/sign-dialog.component.ts +++ b/vsd-app/ClientApp/src/app/sign-dialog/sign-dialog.component.ts @@ -8,7 +8,6 @@ import { SignaturePad } from 'angular2-signaturepad/signature-pad'; styleUrls: ['./sign-dialog.component.scss'] }) export class SignPadDialog implements OnInit { - public signatureImage: any; wasSigned: boolean = false; signatureData: string; @@ -17,17 +16,17 @@ export class SignPadDialog implements OnInit { @ViewChild(SignaturePad) signaturePad: SignaturePad; - signaturePadOptions: Object = { // passed through to szimek/signature_pad constructor - 'minWidth': 0.3, - 'maxWidth': 2.5, - 'canvasWidth': 600, - 'canvasHeight': 200, - 'penColor': '#000', - 'backgroundColor': 'rgba(255, 255, 255, 0)' + signaturePadOptions: Object = { + // passed through to szimek/signature_pad constructor + minWidth: 0.3, + maxWidth: 2.5, + canvasWidth: 600, + canvasHeight: 200, + penColor: '#000', + backgroundColor: 'rgba(255, 255, 255, 0)' }; - constructor(public dialogRef: MatDialogRef) { - } + constructor(public dialogRef: MatDialogRef) {} clearSignature() { this.wasSigned = false; @@ -37,18 +36,17 @@ export class SignPadDialog implements OnInit { acceptSignature() { if (this.wasSigned) { - var resizedCanvas = document.createElement("canvas"); - var resizedContext = resizedCanvas.getContext("2d"); + var resizedCanvas = document.createElement('canvas'); + var resizedContext = resizedCanvas.getContext('2d'); resizedCanvas.height = this.CRM_HEIGHT; resizedCanvas.width = this.CRM_WIDTH; - var canvas = document.querySelectorAll(".signature-pad > signature-pad > canvas")[0] as CanvasImageSource; + var canvas = document.querySelectorAll('.signature-pad > signature-pad > canvas')[0] as CanvasImageSource; resizedContext.drawImage(canvas, 0, 0, this.CRM_WIDTH, this.CRM_HEIGHT); - let signatureData = resizedCanvas.toDataURL();; - + let signatureData = resizedCanvas.toDataURL(); + this.signatureData = signatureData; this.dialogRef.close(signatureData); - } - else { + } else { this.dialogRef.close(); } } @@ -62,7 +60,5 @@ export class SignPadDialog implements OnInit { this.wasSigned = true; } - ngOnInit() { - } - + ngOnInit() {} } diff --git a/vsd-app/ClientApp/src/app/submit-invoice/submit-invoice.component.scss b/vsd-app/ClientApp/src/app/submit-invoice/submit-invoice.component.scss index 81a34a05..c8e77712 100644 --- a/vsd-app/ClientApp/src/app/submit-invoice/submit-invoice.component.scss +++ b/vsd-app/ClientApp/src/app/submit-invoice/submit-invoice.component.scss @@ -152,8 +152,8 @@ textarea.form-control { margin-bottom: 5px; } - input[type="checkbox"], - input[type="radio"] { + input[type='checkbox'], + input[type='radio'] { margin-right: 5px; } @@ -168,7 +168,7 @@ textarea.form-control { } ::ng-deep .terms { - input[type="text"] { + input[type='text'] { margin-left: 15px; } @@ -376,7 +376,7 @@ hr { .form-totals { .gst { margin-bottom: 15px; - margin-top: 15px; + margin-top: 15px; font-size: 18px; } @@ -442,11 +442,11 @@ hr { } .header-alert { - color: #CE3E39 + color: #ce3e39; } .link-span { color: #0c5cb1; text-decoration: underline; cursor: pointer; -} \ No newline at end of file +} diff --git a/vsd-app/ClientApp/src/app/submit-invoice/submit-invoice.component.spec.ts b/vsd-app/ClientApp/src/app/submit-invoice/submit-invoice.component.spec.ts index d27e6872..54255de5 100644 --- a/vsd-app/ClientApp/src/app/submit-invoice/submit-invoice.component.spec.ts +++ b/vsd-app/ClientApp/src/app/submit-invoice/submit-invoice.component.spec.ts @@ -1,24 +1,21 @@ - import { TestBed, async, ComponentFixture, ComponentFixtureAutoDetect } from '@angular/core/testing'; -import { BrowserModule, By } from "@angular/platform-browser"; +import { BrowserModule, By } from '@angular/platform-browser'; import { SubmitInvoiceComponent } from './submit-invoice.component'; let component: SubmitInvoiceComponent; let fixture: ComponentFixture; describe('SubmitInvoice component', () => { - beforeEach(async(() => { - TestBed.configureTestingModule({ - declarations: [SubmitInvoiceComponent ], - imports: [ BrowserModule ], - providers: [ - { provide: ComponentFixtureAutoDetect, useValue: true } - ] - }); - fixture = TestBed.createComponent(SubmitInvoiceComponent); - component = fixture.componentInstance; - })); + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [SubmitInvoiceComponent], + imports: [BrowserModule], + providers: [{ provide: ComponentFixtureAutoDetect, useValue: true }] + }); + fixture = TestBed.createComponent(SubmitInvoiceComponent); + component = fixture.componentInstance; + })); - it('should do something', async(() => { - expect(true).toEqual(true); - })); + it('should do something', async(() => { + expect(true).toEqual(true); + })); }); diff --git a/vsd-app/ClientApp/src/app/submit-invoice/submit-invoice.component.ts b/vsd-app/ClientApp/src/app/submit-invoice/submit-invoice.component.ts index bc1bb807..fb59c3bb 100644 --- a/vsd-app/ClientApp/src/app/submit-invoice/submit-invoice.component.ts +++ b/vsd-app/ClientApp/src/app/submit-invoice/submit-invoice.component.ts @@ -27,10 +27,9 @@ import { LookupService } from '../services/lookup.service'; styleUrls: ['./submit-invoice.component.scss'], providers: [ { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, - { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }, - ], + { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS } + ] }) - export class SubmitInvoiceComponent extends FormBase implements OnInit { postalRegex = POSTAL_CODE; dataLoaded = false; @@ -54,8 +53,8 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { public showCancelPanel: boolean = false; public showPrintView: boolean = false; - invoiceSubTotal: number = 0.00; - invoiceGrandTotal: number = 0.00; + invoiceSubTotal: number = 0.0; + invoiceGrandTotal: number = 0.0; isVendorValid: boolean = false; didValidateVendor: boolean = false; @@ -70,8 +69,8 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { isIE: boolean = false; - cvapEmail: string = ""; - cvapCounsellingEmail: string = ""; + cvapEmail: string = ''; + cvapCounsellingEmail: string = ''; constructor( private justiceDataService: JusticeApplicationDataService, @@ -79,7 +78,7 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { public snackBar: MatSnackBar, private dialog: MatDialog, private aemService: AEMService, - private lookupService: LookupService, + private lookupService: LookupService ) { super(); this.formFullyValidated = false; @@ -89,7 +88,6 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { var ua = window.navigator.userAgent; this.isIE = /MSIE|Trident/.test(ua); - this.form = this.buildInvoiceForm(); this.lineItems = this.form.get('invoiceDetails.lineItems') as FormArray; this.lineItemsControls = this.form.get('invoiceDetails.lineItems') as FormArray; @@ -97,8 +95,7 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { if (this.lookupService.cvapEmail) { this.cvapEmail = this.lookupService.cvapEmail; this.cvapCounsellingEmail = this.lookupService.cvapCounsellingEmail; - } - else { + } else { this.lookupService.getCVAPEmails().subscribe((res) => { this.cvapEmail = res.cvapEmail; this.cvapCounsellingEmail = res.cvapCounsellingEmail; @@ -117,8 +114,8 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { this.showReviewPanel = false; this.showSuccessPanel = false; this.showCancelPanel = false; - this.invoiceSubTotal = 0.00; - this.invoiceGrandTotal = 0.00; + this.invoiceSubTotal = 0.0; + this.invoiceGrandTotal = 0.0; this.isVendorValid = false; this.didValidateVendor = false; this.isCounsellorValid = false; @@ -136,39 +133,39 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { printInvoice() { let invoice = { - InvoiceDetails: this.form.get('invoiceDetails').value, + InvoiceDetails: this.form.get('invoiceDetails').value }; invoice.InvoiceDetails.exemptFromGst = !invoice.InvoiceDetails.gstApplicable; // console.log(invoice); let invoiceDate = moment(invoice.InvoiceDetails.invoiceDate).toDate(); let date_string = invoiceDate.getFullYear() + MONTHS[invoiceDate.getMonth()] + invoiceDate.getDate(); - - this.getAEMPDF().then((pdf: string) => { - let downloadLink = document.createElement("a"); - downloadLink.href = "data:application/pdf;base64," + pdf; - downloadLink.download = `Invoice-${invoice.InvoiceDetails.invoiceNumber}-${date_string}.pdf`; - downloadLink.target = "_blank"; - - document.body.appendChild(downloadLink); - downloadLink.click(); - document.body.removeChild(downloadLink); - }).catch((err) => { - console.log("error getting pdf"); - console.log(err); - }); - + this.getAEMPDF() + .then((pdf: string) => { + let downloadLink = document.createElement('a'); + downloadLink.href = 'data:application/pdf;base64,' + pdf; + downloadLink.download = `Invoice-${invoice.InvoiceDetails.invoiceNumber}-${date_string}.pdf`; + downloadLink.target = '_blank'; + + document.body.appendChild(downloadLink); + downloadLink.click(); + document.body.removeChild(downloadLink); + }) + .catch((err) => { + console.log('error getting pdf'); + console.log(err); + }); } @HostListener('window:afterprint') onafterprint() { - document.querySelectorAll(".slide-close")[0].classList.remove("hide-for-print") + document.querySelectorAll('.slide-close')[0].classList.remove('hide-for-print'); window.scroll(0, 0); this.showPrintView = false; } - invoiceEdit(id: string = ""): void { + invoiceEdit(id: string = ''): void { this.showFormPanel = true; this.showReviewPanel = false; this.showSuccessPanel = false; @@ -177,13 +174,11 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { setTimeout(() => { if (!id) { window.scroll(0, 0); - } - else { + } else { let el = document.getElementById(id); el.scrollIntoView({ behavior: 'smooth', block: 'start' }); } }, 100); - } invoiceReview(): void { @@ -207,7 +202,7 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { let self = this; let dialogRef = this.dialog.open(CancelDialog, { autoFocus: false, - data: { type: "Invoice" } + data: { type: 'Invoice' } }); dialogRef.afterClosed().subscribe((res: any) => { @@ -233,9 +228,9 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { } calculateAllTotals(): void { - let invoiceSubTotal = 0.00; + let invoiceSubTotal = 0.0; let invoiceItems = this.form.get('invoiceDetails.lineItems'); - invoiceItems.controls.forEach(item => { + invoiceItems.controls.forEach((item) => { let sessionHours = item.get('sessionHours').value || 0; invoiceSubTotal += sessionHours; }); @@ -245,11 +240,11 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { createLineItem(sessionHours: string = ''): FormGroup { return this.fb.group({ - counsellingType: [0, [Validators.required, Validators.min(100000000)]], // Counselling Session: 100000000 Court Support Counselling: 100000001 Psycho-educational sessions: 100000002 --- VALIDATE THESE NUMBERS ARE CORRECT + counsellingType: [0, [Validators.required, Validators.min(100000000)]], // Counselling Session: 100000000 Court Support Counselling: 100000001 Psycho-educational sessions: 100000002 --- VALIDATE THESE NUMBERS ARE CORRECT missedSession: [false], sessionDate: ['', Validators.required], sessionHours: [0, [Validators.required, Validators.min(0.5)]], - sessionAmount: [0], // used for row calculation, not required for submission - could probably subscribe to value changes on controls that need it + sessionAmount: [0] // used for row calculation, not required for submission - could probably subscribe to value changes on controls that need it }); } @@ -272,21 +267,16 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { dialogConfig.autoFocus = true; const dialogRef = this.dialog.open(SignPadDialog, dialogConfig); - dialogRef.afterClosed().subscribe( - data => { - var patchObject = {}; - patchObject[control] = data; - this.form.get(group).patchValue( - patchObject - ); - } - ); + dialogRef.afterClosed().subscribe((data) => { + var patchObject = {}; + patchObject[control] = data; + this.form.get(group).patchValue(patchObject); + }); } isControlValid(formControl: FormGroup, field: string) { let formField = formControl; - if (formField == null) - return true; + if (formField == null) return true; return formField.controls[field].valid || !formField.controls[field].touched; } @@ -297,7 +287,7 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { this.formFullyValidated = true; this.invoiceReview(); } else { - console.log("form not validated"); + console.log('form not validated'); this.formFullyValidated = false; this.markAsTouched(); } @@ -317,43 +307,47 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { this.submitting = true; this.formFullyValidated = true; const formData = { - InvoiceDetails: this.form.get('invoiceDetails').value, + InvoiceDetails: this.form.get('invoiceDetails').value }; formData.InvoiceDetails.exemptFromGst = !formData.InvoiceDetails.gstApplicable; - this.getInvoicePDF(formData).then((pdfs: DocumentCollectioninformation[]) => { - formData.DocumentCollection = pdfs; - - this.save(formData).subscribe( - data => { - this.submitting = false; - if (data['IsSuccess'] == true) { - this.invoiceSuccess(); - } - else { - this.snackBar.open('Error submitting invoice. ' + data['message'], 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); - console.log('Error submitting invoice. ' + data['message']); + this.getInvoicePDF(formData) + .then((pdfs: DocumentCollectioninformation[]) => { + formData.DocumentCollection = pdfs; + + this.save(formData).subscribe( + (data) => { + this.submitting = false; + if (data['IsSuccess'] == true) { + this.invoiceSuccess(); + } else { + this.snackBar.open('Error submitting invoice. ' + data['message'], 'Fail', { + duration: 3500, + panelClass: ['red-snackbar'] + }); + console.log('Error submitting invoice. ' + data['message']); + if (this.isIE) { + alert('Encountered an error. Please use another browser as this may resolve the problem.'); + } + } + }, + (error) => { + this.submitting = false; + this.snackBar.open('Error submitting invoice', 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); + console.log('Error submitting invoice'); if (this.isIE) { - alert("Encountered an error. Please use another browser as this may resolve the problem.") + alert('Encountered an error. Please use another browser as this may resolve the problem.'); } - } - }, - error => { - this.submitting = false; - this.snackBar.open('Error submitting invoice', 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); - console.log('Error submitting invoice'); - if (this.isIE) { - alert("Encountered an error. Please use another browser as this may resolve the problem.") - } - }, - () => { } - ); - }).catch(err => { - this.submitting = false; - console.log(err); - }); + }, + () => {} + ); + }) + .catch((err) => { + this.submitting = false; + console.log(err); + }); } else { - console.log("form not validated"); + console.log('form not validated'); this.formFullyValidated = false; this.markAsTouched(); } @@ -372,45 +366,48 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { this.submitting = true; this.formFullyValidated = true; const formData = { - InvoiceDetails: this.form.get('invoiceDetails').value, + InvoiceDetails: this.form.get('invoiceDetails').value }; formData.InvoiceDetails.exemptFromGst = !formData.InvoiceDetails.gstApplicable; - this.getInvoicePDF(formData).then((pdfs: DocumentCollectioninformation[]) => { - formData.DocumentCollection = pdfs; - - this.save(formData).subscribe( - data => { - this.submitting = false; - if (data['IsSuccess'] == true) { - this.invoiceEdit(); - this.cloneInvoice(_.cloneDeep(this.form)); - } - else { - this.snackBar.open('Error submitting invoice. ' + data['message'], 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); - console.log('Error submitting invoice. ' + data['message']); + this.getInvoicePDF(formData) + .then((pdfs: DocumentCollectioninformation[]) => { + formData.DocumentCollection = pdfs; + + this.save(formData).subscribe( + (data) => { + this.submitting = false; + if (data['IsSuccess'] == true) { + this.invoiceEdit(); + this.cloneInvoice(_.cloneDeep(this.form)); + } else { + this.snackBar.open('Error submitting invoice. ' + data['message'], 'Fail', { + duration: 3500, + panelClass: ['red-snackbar'] + }); + console.log('Error submitting invoice. ' + data['message']); + if (this.isIE) { + alert('Encountered an error. Please use another browser as this may resolve the problem.'); + } + } + }, + (error) => { + this.submitting = false; + this.snackBar.open('Error submitting invoice', 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); + console.log('Error submitting invoice'); if (this.isIE) { - alert("Encountered an error. Please use another browser as this may resolve the problem.") + alert('Encountered an error. Please use another browser as this may resolve the problem.'); } - } - }, - error => { - this.submitting = false; - this.snackBar.open('Error submitting invoice', 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); - console.log('Error submitting invoice'); - if (this.isIE) { - alert("Encountered an error. Please use another browser as this may resolve the problem.") - } - }, - () => { } - ); - - }).catch(err => { - this.submitting = false; - console.log(err); - }); + }, + () => {} + ); + }) + .catch((err) => { + this.submitting = false; + console.log(err); + }); } else { - console.log("form not validated"); + console.log('form not validated'); this.formFullyValidated = false; this.markAsTouched(); } @@ -419,11 +416,12 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { save(formData: CounsellorInvoice): Subject<{}> { const subResult = new Subject<{}>(); - this.justiceDataService.submitCounsellorInvoice(formData) - .subscribe(res => { + this.justiceDataService.submitCounsellorInvoice(formData).subscribe( + (res) => { subResult.next(res); - }, err => subResult.next(false)); - + }, + (err) => subResult.next(false) + ); return subResult; } @@ -436,54 +434,62 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { let invoiceDate = moment(invoice.InvoiceDetails.invoiceDate).toDate(); let date_string = invoiceDate.getFullYear() + MONTHS[invoiceDate.getMonth()] + invoiceDate.getDate(); - promise_array.push(new Promise((resolve, reject) => { - this.getAEMPDF().then((pdf: string) => { - ret.push({ - body: pdf, - filename: `Invoice-${invoice.InvoiceDetails.invoiceNumber}-${date_string}.pdf`, - subject: "", - }); - resolve(); - }).catch((err) => { + promise_array.push( + new Promise((resolve, reject) => { + this.getAEMPDF() + .then((pdf: string) => { + ret.push({ + body: pdf, + filename: `Invoice-${invoice.InvoiceDetails.invoiceNumber}-${date_string}.pdf`, + subject: '' + }); + resolve(); + }) + .catch((err) => { + console.log(err); + reject(); + }); + }) + ); + + Promise.all(promise_array) + .then((res) => { + resolve(ret); + }) + .catch((err) => { console.log(err); - reject(); + reject(err); }); - })); - - Promise.all(promise_array).then((res) => { - resolve(ret); - }).catch((err) => { - console.log(err); - reject(err); - }); }); } getAEMPDF(): Promise { return new Promise((resolve, reject) => { let invoice = { - InvoiceDetails: this.form.get('invoiceDetails').value, + InvoiceDetails: this.form.get('invoiceDetails').value }; invoice.InvoiceDetails.exemptFromGst = !invoice.InvoiceDetails.gstApplicable; - invoice.InvoiceDetails.claimantsFullName = invoice.InvoiceDetails.claimantsFirstName + ' ' + invoice.InvoiceDetails.claimantsLastName; + invoice.InvoiceDetails.claimantsFullName = + invoice.InvoiceDetails.claimantsFirstName + ' ' + invoice.InvoiceDetails.claimantsLastName; - invoice.InvoiceDetails.lineItems.forEach(line => { + invoice.InvoiceDetails.lineItems.forEach((line) => { line.counsellingTypeName = COUNSELLING_TYPES[line.counsellingType]; }); - this.aemService.getInvoicePDF(invoice).subscribe((res: any) => { - console.log(res); - if (res.responseMessage) { - resolve(res.responseMessage); - } - else { - reject(res); - } - }, + this.aemService.getInvoicePDF(invoice).subscribe( + (res: any) => { + console.log(res); + if (res.responseMessage) { + resolve(res.responseMessage); + } else { + reject(res); + } + }, (err) => { reject(err); console.log(err); - }); + } + ); }); } @@ -497,12 +503,20 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { this.lineItems = this.form.get('invoiceDetails.lineItems') as FormArray; this.lineItemsControls = this.form.get('invoiceDetails.lineItems') as FormArray; - this.form.get('invoiceDetails.counsellorRegistrationNumber').patchValue(formCopy.get('invoiceDetails.counsellorRegistrationNumber').value); - this.form.get('invoiceDetails.counsellorLastName').patchValue(formCopy.get('invoiceDetails.counsellorLastName').value); + this.form + .get('invoiceDetails.counsellorRegistrationNumber') + .patchValue(formCopy.get('invoiceDetails.counsellorRegistrationNumber').value); + this.form + .get('invoiceDetails.counsellorLastName') + .patchValue(formCopy.get('invoiceDetails.counsellorLastName').value); this.form.get('invoiceDetails.vendorNumber').patchValue(formCopy.get('invoiceDetails.vendorNumber').value); this.form.get('invoiceDetails.vendorPostalCode').patchValue(formCopy.get('invoiceDetails.vendorPostalCode').value); - this.form.get('invoiceDetails.submitterFullName').patchValue(formCopy.get('invoiceDetails.submitterFullName').value); - this.form.get('invoiceDetails.submitterEmailAddress').patchValue(formCopy.get('invoiceDetails.submitterEmailAddress').value); + this.form + .get('invoiceDetails.submitterFullName') + .patchValue(formCopy.get('invoiceDetails.submitterFullName').value); + this.form + .get('invoiceDetails.submitterEmailAddress') + .patchValue(formCopy.get('invoiceDetails.submitterEmailAddress').value); } private buildInvoiceForm(): FormGroup { @@ -526,8 +540,8 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { submitterFullName: ['', Validators.required], submitterEmailAddress: ['', [Validators.required, Validators.email]], - declaredAndSigned: ['', Validators.required], - }), + declaredAndSigned: ['', Validators.required] + }) }); } @@ -543,41 +557,43 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { this.didValidateVendor = true; this.isVendorValid = res.IsSuccess; }); - } - else { + } else { this.isVendorValid = false; } if (vendorNumber && vendorPostalCode && counsellorNumber && counsellorLastName) { - this.justiceDataService.validateVendorAndCounsellor(vendorNumber, vendorPostalCode, counsellorNumber, counsellorLastName).subscribe((res: any) => { - this.didValidateCounsellor = true; - this.isCounsellorValid = res.IsSuccess; - if (this.isCounsellorValid) { - this.counsellor_level = res.CounsellorLevel; - - if (this.form.get('invoiceDetails.gstApplicable').value == true) { - this.checkCousellorLevel(); + this.justiceDataService + .validateVendorAndCounsellor(vendorNumber, vendorPostalCode, counsellorNumber, counsellorLastName) + .subscribe((res: any) => { + this.didValidateCounsellor = true; + this.isCounsellorValid = res.IsSuccess; + if (this.isCounsellorValid) { + this.counsellor_level = res.CounsellorLevel; + + if (this.form.get('invoiceDetails.gstApplicable').value == true) { + this.checkCousellorLevel(); + } } - } - }); + }); } break; } case 'counsellor': { if (vendorNumber && vendorPostalCode && counsellorNumber && counsellorLastName) { - this.justiceDataService.validateVendorAndCounsellor(vendorNumber, vendorPostalCode, counsellorNumber, counsellorLastName).subscribe((res: any) => { - this.didValidateCounsellor = true; - this.isCounsellorValid = res.IsSuccess; - if (this.isCounsellorValid) { - this.counsellor_level = res.CounsellorLevel; - - if (this.form.get('invoiceDetails.gstApplicable').value == true) { - this.checkCousellorLevel(); + this.justiceDataService + .validateVendorAndCounsellor(vendorNumber, vendorPostalCode, counsellorNumber, counsellorLastName) + .subscribe((res: any) => { + this.didValidateCounsellor = true; + this.isCounsellorValid = res.IsSuccess; + if (this.isCounsellorValid) { + this.counsellor_level = res.CounsellorLevel; + + if (this.form.get('invoiceDetails.gstApplicable').value == true) { + this.checkCousellorLevel(); + } } - } - }); - } - else { + }); + } else { this.isCounsellorValid = false; } break; @@ -589,7 +605,10 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { } checkCousellorLevel() { - if (this.form.get('invoiceDetails.gstApplicable').value == true && (this.counsellor_level == 4 || this.counsellor_level == 5)) { + if ( + this.form.get('invoiceDetails.gstApplicable').value == true && + (this.counsellor_level == 4 || this.counsellor_level == 5) + ) { let dialogRef = this.dialog.open(GSTWarningDialog, { autoFocus: false, data: {} @@ -607,30 +626,35 @@ export class SubmitInvoiceComponent extends FormBase implements OnInit { let data = []; for (let i = 0; i < lineItems.length; ++i) { let item = this.lineItems.at(i) as FormGroup; - data.push({ type: item.get("counsellingType").value, date: item.get("sessionDate").value.toString() }); + data.push({ type: item.get('counsellingType').value, date: item.get('sessionDate').value.toString() }); } - let duplicates = data.filter((d1, index, self) => self.findIndex(d2 => d1.type == d2.type && d1.date == d2.date) != index); + let duplicates = data.filter( + (d1, index, self) => self.findIndex((d2) => d1.type == d2.type && d1.date == d2.date) != index + ); if (duplicates.length > 0) { this.hasDuplicateLineItem = true; this.dialog.open(MessageDialog, { autoFocus: false, - data: { title: "Duplicate Line Item", message: "This counselling type already entered for this date, please review session date." } + data: { + title: 'Duplicate Line Item', + message: 'This counselling type already entered for this date, please review session date.' + } }); - } - else { + } else { this.hasDuplicateLineItem = false; } } } -const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; const COUNSELLING_TYPES = { - 100000000: "Counselling Session", - 100000001: "Court Supporting Counselling", - 100000002: "Psycho-educational sessions", -} - -const DUPLICATE_LINE_ITEMS_TITLE = "Duplicate Line Items"; -const DUPLICATE_LINE_ITEMS_MESSAGE = "Multiple line items detected with same session date and counselling type, please review line items before submitting this invoice."; + 100000000: 'Counselling Session', + 100000001: 'Court Supporting Counselling', + 100000002: 'Psycho-educational sessions' +}; + +const DUPLICATE_LINE_ITEMS_TITLE = 'Duplicate Line Items'; +const DUPLICATE_LINE_ITEMS_MESSAGE = + 'Multiple line items detected with same session date and counselling type, please review line items before submitting this invoice.'; diff --git a/vsd-app/ClientApp/src/app/summary-of-benefits/benefit-list.ts b/vsd-app/ClientApp/src/app/summary-of-benefits/benefit-list.ts index 51a6f9d0..e0f8e8a2 100644 --- a/vsd-app/ClientApp/src/app/summary-of-benefits/benefit-list.ts +++ b/vsd-app/ClientApp/src/app/summary-of-benefits/benefit-list.ts @@ -1,13 +1,9 @@ export class BenefitLists { - static VictimBenefitList = [ { title: 'Counselling services or expenses', target: 'All victims of crime', - examples: [ - 'Counselling Sessions', - 'Psycho-educational sessions to others who support the victim', - ] + examples: ['Counselling Sessions', 'Psycho-educational sessions to others who support the victim'] }, { title: 'Medical services or expenses', @@ -24,112 +20,101 @@ export class BenefitLists { target: 'Victims who need dental care because of their injuries from the crime', examples: [ 'Diagnosis and treatment by a dentis or dental health professional', - 'Bridges, crowns, dengures, and other dental appliances or devices', + 'Bridges, crowns, dengures, and other dental appliances or devices' ] }, { title: 'Prescription drug expenses', - target: 'Victims who need prescription drugs to recover from, or manage the effects of, their injuries from the crime', - examples: [ - 'Medications prescribed by a doctor, dentist, or podiatrist', - ] + target: + 'Victims who need prescription drugs to recover from, or manage the effects of, their injuries from the crime', + examples: ['Medications prescribed by a doctor, dentist, or podiatrist'] }, { title: 'Protective measures, services, or expenses', - target: 'Victims who are at risk of additional harm from the perpetrator or are traumatized to the extent that they cannot perform regular daily activities', + target: + 'Victims who are at risk of additional harm from the perpetrator or are traumatized to the extent that they cannot perform regular daily activities', examples: [ 'Security or communication equipment and services', 'Courses for personal protection or security', - 'Relocation expenses', + 'Relocation expenses' ] }, { title: 'Income support', - target: 'Victims whose injuries have a short-term or long-term effect on their ability to work and who had a job when the crime occurred (special eligibility issues for minors)', - examples: [ - 'Monthly payments to assist in financially supporting the victim', - ] + target: + 'Victims whose injuries have a short-term or long-term effect on their ability to work and who had a job when the crime occurred (special eligibility issues for minors)', + examples: ['Monthly payments to assist in financially supporting the victim'] }, { title: 'Lost earning capacity', - target: 'Victims whose injuries have a long-term effect on their ability to work and who did not have a job when the crime occurred (special eligibility issues for minors)', - examples: [ - 'Monthly payments to assist in financially supporting the victim', - ] + target: + 'Victims whose injuries have a long-term effect on their ability to work and who did not have a job when the crime occurred (special eligibility issues for minors)', + examples: ['Monthly payments to assist in financially supporting the victim'] }, { title: 'Vocational services or expenses', - target: 'Victims whose injuries prevent them from returning to their job and who need training or education to re-enter the workforce', + target: + 'Victims whose injuries prevent them from returning to their job and who need training or education to re-enter the workforce', examples: [ 'Education and training courses', 'Programs to improve skills and qualifications', - 'Programs to prepare for, or find, employment', + 'Programs to prepare for, or find, employment' ] }, { title: 'Transportation and related expenses, and transportation related childcare', - target: 'Victims who have to travel some distance to obtain medical, dental, counselling, or vocational services provided as crime victim assistance benefits', + target: + 'Victims who have to travel some distance to obtain medical, dental, counselling, or vocational services provided as crime victim assistance benefits', examples: [ 'Transportation expenses such as bus fare, air fare, or mileage expenses', 'Meals and accomodation', - 'Childcare while attending appointments', + 'Childcare while attending appointments' ] }, { title: 'Repair or replacement of damaged or destroyed personal property', - target: 'Victims whose eyeglasses/contacts, disability aids, or articles of clothing were damaged or destroyed because of the crime', - examples: [ - 'Eyeglass frames', - 'Prescription lenses', - 'Various types of disability aids', - 'Clothing', - ] + target: + 'Victims whose eyeglasses/contacts, disability aids, or articles of clothing were damaged or destroyed because of the crime', + examples: ['Eyeglass frames', 'Prescription lenses', 'Various types of disability aids', 'Clothing'] }, { title: 'Disability aids', - target: 'Victims who need disability aids because of their injuries from the crime, to reduce the effects of the injuries, improve their quality of life, and assist in daily living', - examples: [ - 'Mobility aids', - 'Communication aids', - 'Vision aids', - 'Specialized clothing' - ] + target: + 'Victims who need disability aids because of their injuries from the crime, to reduce the effects of the injuries, improve their quality of life, and assist in daily living', + examples: ['Mobility aids', 'Communication aids', 'Vision aids', 'Specialized clothing'] }, { title: 'Childcare services or expenses (see also under transportation)', - target: 'Victims who have a disability because of the crime that prevents them from providing care for their children (and no one else in the household can perform the household tasks)', - examples: [ - 'Childcare', - ] + target: + 'Victims who have a disability because of the crime that prevents them from providing care for their children (and no one else in the household can perform the household tasks)', + examples: ['Childcare'] }, { title: 'Homemaker services or expenses', - target: 'Victims who have a disability because of the crime that prevents them from doing household tasks (and no one else in the household can perform the household tasks)', - examples: [ - 'Help with shopping, clearning, cooking, and other household tasks', - ] + target: + 'Victims who have a disability because of the crime that prevents them from doing household tasks (and no one else in the household can perform the household tasks)', + examples: ['Help with shopping, clearning, cooking, and other household tasks'] }, { title: 'Personal care services or expenses', - target: 'Victims who have a disability because of the crime that prevents them from performing personal care tasks', - examples: [ - 'Help with bathing, dressing, toileting, and other personal care tasks', - ] + target: + 'Victims who have a disability because of the crime that prevents them from performing personal care tasks', + examples: ['Help with bathing, dressing, toileting, and other personal care tasks'] }, { title: 'Home modification expenses', - target: 'Victims who have a disability because of the crime and need modifications made to their home to assist them in daily activities', + target: + 'Victims who have a disability because of the crime and need modifications made to their home to assist them in daily activities', examples: [ 'Structural changes such as replacing steps with a ramp, widening doorways, constructing custom showers, etc.', - 'Installed equipment such as wheelchair lifts, bath lifts or shower stalls, wing taps on sinks, etc.', + 'Installed equipment such as wheelchair lifts, bath lifts or shower stalls, wing taps on sinks, etc.' ] }, { title: 'Home maintenance expenses', - target: 'Victims who have a disability because of the that prevents them from maintaining their home (and no one else in the household can maintain the home)', - examples: [ - 'A monthly allowance for home maintenance expenses', - ] + target: + 'Victims who have a disability because of the that prevents them from maintaining their home (and no one else in the household can maintain the home)', + examples: ['A monthly allowance for home maintenance expenses'] }, { title: 'Moving expenses', @@ -137,141 +122,132 @@ export class BenefitLists { examples: [ 'Moving expenses for the victim and family and their household goods', 'Rental security deposit', - 'Connection fees for phone and utility', + 'Connection fees for phone and utility' ] }, { title: 'Vehicle modification or acquisition', - target: 'Victims who have a long-term disability because of the crime and need an accessible vehicle (to drive or be driven in) for greater independence', + target: + 'Victims who have a long-term disability because of the crime and need an accessible vehicle (to drive or be driven in) for greater independence', examples: [ 'Installed equipment such as hand controls or wheelchair lift', - 'Purchase or lease of an accessible vehicle', + 'Purchase or lease of an accessible vehicle' ] }, { title: 'Maintenance for a child born as a result of a prescribed offence', target: 'Victims who conceived a child as a result of the crime and are financially supporting the child', - examples: [ - 'Monthly payments to assist in financially supporting the child', - ] + examples: ['Monthly payments to assist in financially supporting the child'] }, { title: 'Crime scene cleaning', - target: 'Victims who were injured at their home or in their vehicle and need specialized cleaning of the home or vehicle due to the nature of the crime.', + target: + 'Victims who were injured at their home or in their vehicle and need specialized cleaning of the home or vehicle due to the nature of the crime.', examples: [ 'Specialized cleaning and disinfecting of contaminated areas', - 'Replacement of contaminated flooring, wall covering, or other built-in features', + 'Replacement of contaminated flooring, wall covering, or other built-in features' ] - }, + } ]; static IfmBenefitList = [ { title: 'Counselling services or expenses', - target: 'Immediate Family Members who need counselling to recover from the psychological injury caused by the crime', - examples: [ - 'Counselling Sessions', - ] + target: + 'Immediate Family Members who need counselling to recover from the psychological injury caused by the crime', + examples: ['Counselling Sessions'] }, { title: 'Prescription drug expenses', - target: 'Immediate Family Members who need prescription drugs to recover from the psychological injury caused by the crime', - examples: [ - 'Medications prescribed by a doctor', - ] + target: + 'Immediate Family Members who need prescription drugs to recover from the psychological injury caused by the crime', + examples: ['Medications prescribed by a doctor'] }, { title: 'Transportation and related expenses, and transportation related childcare', - target: 'Immediate Family Members who have to travel some distance to obtain counselling or vocational services provided as CVAP benefits. Immediate Family Members of deceased victims who have to travel over 100 km to attend legal proceedings regarding the death', + target: + 'Immediate Family Members who have to travel some distance to obtain counselling or vocational services provided as CVAP benefits. Immediate Family Members of deceased victims who have to travel over 100 km to attend legal proceedings regarding the death', examples: [ 'Transportation expenses such as bus fare, air fare, mileage expenses', 'Meals and accommodation', - 'Childcare while attending appointments', + 'Childcare while attending appointments' ] }, { title: 'Funeral Expenses', target: 'Immediate Family Members of deceased victims who have to pay for funeral and related costs', - examples: [ - 'Costs involved in the funeral service, burial, cremation or related ceremony', - ] + examples: ['Costs involved in the funeral service, burial, cremation or related ceremony'] }, { title: 'Bereavement leave', - target: 'Immediate Family Members of deceased victims who lose earnings from taking time off work for the funeral or other matters related to the victim’s death', - examples: [ - 'An amount to help offset the loss of earnings', - ] + target: + 'Immediate Family Members of deceased victims who lose earnings from taking time off work for the funeral or other matters related to the victim’s death', + examples: ['An amount to help offset the loss of earnings'] }, { title: 'Income support', - target: 'Spouses of deceased victims, Children of deceased victims, Other immeditate family members of deceased victims if they were financially dependent on the victim', - examples: [ - 'Monthly payments to assist in financially supporting the immediate family member', - ] + target: + 'Spouses of deceased victims, Children of deceased victims, Other immeditate family members of deceased victims if they were financially dependent on the victim', + examples: ['Monthly payments to assist in financially supporting the immediate family member'] }, { title: 'Loss of parental guidance for a minor child', target: 'Children of deceased victims who were under 19 when their parent was killed', - examples: [ - 'A set amount as a contribution toward loss of parental guidance', - ] + examples: ['A set amount as a contribution toward loss of parental guidance'] }, { title: 'Vocational services or expenses', - target: 'Spouses of deceased victims who need training or education to prepare for employment or improve their earning capacity (and who are eligible for income support benefits from CVAP)', + target: + 'Spouses of deceased victims who need training or education to prepare for employment or improve their earning capacity (and who are eligible for income support benefits from CVAP)', examples: [ 'Education and training courses', 'Programs to improve skills and qualifications', - 'Programs to prepare for, or find, employment', + 'Programs to prepare for, or find, employment' ] }, { title: 'Childcare services or expenses (see also under transportation)', - target: 'Spouses of deceased victims who need to pay for childcare because there is no one in the household to share this responsibility', - examples: [ - 'Childcare', - ] + target: + 'Spouses of deceased victims who need to pay for childcare because there is no one in the household to share this responsibility', + examples: ['Childcare'] }, { title: 'Homemaker services or expenses', - target: 'Spouses of deceased victims who need to pay for homemaker services because there is no one in the household to share household tasks', - examples: [ - 'Help with shopping, cleaning, cooking, and other household tasks', - ] + target: + 'Spouses of deceased victims who need to pay for homemaker services because there is no one in the household to share household tasks', + examples: ['Help with shopping, cleaning, cooking, and other household tasks'] }, { title: 'Crime scene cleaning', - target: 'Immediate Family Members who need specialized cleaning of the victim’s home or vehicle (if the victim is deceased), or their own home or vehicle, because the crime was committed there', + target: + 'Immediate Family Members who need specialized cleaning of the victim’s home or vehicle (if the victim is deceased), or their own home or vehicle, because the crime was committed there', examples: [ 'Specialized cleaning and disinfecting of contaminated areas', - 'Replacement of contaminated flooring, wall covering, or other built-in features', + 'Replacement of contaminated flooring, wall covering, or other built-in features' ] - }, + } ]; static WitnessBenefitList = [ { title: 'Counselling services or expenses', target: 'Witnesses who need counselling to recover from the psychological injury caused by witnessing the crime.', - examples: [ - 'Counselling Sessions', - ] + examples: ['Counselling Sessions'] }, { title: 'Prescription drug expenses', - target: 'Witnesses who need prescription drugs to recover from the psychological injury caused by witnessing the crime.', - examples: [ - 'Medications prescribed by a doctor', - ] + target: + 'Witnesses who need prescription drugs to recover from the psychological injury caused by witnessing the crime.', + examples: ['Medications prescribed by a doctor'] }, { title: 'Transportation and related expenses, and transportation related childcare', - target: 'Witnesses who have to travel some distance to obtain counselling services provided as crime victim assistance benefits.', + target: + 'Witnesses who have to travel some distance to obtain counselling services provided as crime victim assistance benefits.', examples: [ 'Transportation expenses such as bus fare, air fare, mileage expenses', 'Meals and accommodation', - 'Childcare while attending appointments', + 'Childcare while attending appointments' ] }, { @@ -279,8 +255,8 @@ export class BenefitLists { target: 'Witnesses who need specialized cleaning of their home or vehicle because the crime was committed there.', examples: [ 'Specialized cleaning and disinfecting of contaminated areas', - 'Replacement of contaminated flooring, wall covering, or other built-in features', + 'Replacement of contaminated flooring, wall covering, or other built-in features' ] - }, + } ]; } diff --git a/vsd-app/ClientApp/src/app/summary-of-benefits/summary-of-benefits.component.ts b/vsd-app/ClientApp/src/app/summary-of-benefits/summary-of-benefits.component.ts index ca62e113..0d0b3588 100644 --- a/vsd-app/ClientApp/src/app/summary-of-benefits/summary-of-benefits.component.ts +++ b/vsd-app/ClientApp/src/app/summary-of-benefits/summary-of-benefits.component.ts @@ -8,7 +8,6 @@ import { ApplicationType } from '../shared/enums-list'; styleUrls: ['./summary-of-benefits.component.scss'] }) export class SummaryOfBenefitsDialog implements OnInit { - benefitList: any; formType: ApplicationType; ApplicationType = ApplicationType; @@ -17,8 +16,7 @@ export class SummaryOfBenefitsDialog implements OnInit { showFamilyBenefits: boolean = false; showWitnessBenefits: boolean = false; - constructor(public dialogRef: MatDialogRef, @Inject(MAT_DIALOG_DATA) public data: any) { - } + constructor(public dialogRef: MatDialogRef, @Inject(MAT_DIALOG_DATA) public data: any) {} closeMe(): void { this.dialogRef.close(); diff --git a/vsd-app/ClientApp/src/app/victim-application/victim-application.component.scss b/vsd-app/ClientApp/src/app/victim-application/victim-application.component.scss index c62175b8..14fb6d92 100644 --- a/vsd-app/ClientApp/src/app/victim-application/victim-application.component.scss +++ b/vsd-app/ClientApp/src/app/victim-application/victim-application.component.scss @@ -13,4 +13,4 @@ h2, h3 { margin-top: 30px; margin-bottom: 20px; -} \ No newline at end of file +} diff --git a/vsd-app/ClientApp/src/app/victim-application/victim-application.component.spec.ts b/vsd-app/ClientApp/src/app/victim-application/victim-application.component.spec.ts index 2b379725..42b3c48f 100644 --- a/vsd-app/ClientApp/src/app/victim-application/victim-application.component.spec.ts +++ b/vsd-app/ClientApp/src/app/victim-application/victim-application.component.spec.ts @@ -1,24 +1,21 @@ - import { TestBed, async, ComponentFixture, ComponentFixtureAutoDetect } from '@angular/core/testing'; -import { BrowserModule, By } from "@angular/platform-browser"; +import { BrowserModule, By } from '@angular/platform-browser'; import { VictimApplicationComponent } from './victim-application.component'; let component: VictimApplicationComponent; let fixture: ComponentFixture; describe('VictimApplication component', () => { - beforeEach(async(() => { - TestBed.configureTestingModule({ - declarations: [ VictimApplicationComponent ], - imports: [ BrowserModule ], - providers: [ - { provide: ComponentFixtureAutoDetect, useValue: true } - ] - }); - fixture = TestBed.createComponent(VictimApplicationComponent); - component = fixture.componentInstance; - })); + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [VictimApplicationComponent], + imports: [BrowserModule], + providers: [{ provide: ComponentFixtureAutoDetect, useValue: true }] + }); + fixture = TestBed.createComponent(VictimApplicationComponent); + component = fixture.componentInstance; + })); - it('should do something', async(() => { - expect(true).toEqual(true); - })); + it('should do something', async(() => { + expect(true).toEqual(true); + })); }); diff --git a/vsd-app/ClientApp/src/app/victim-application/victim-application.component.ts b/vsd-app/ClientApp/src/app/victim-application/victim-application.component.ts index 7346365f..016ebf51 100644 --- a/vsd-app/ClientApp/src/app/victim-application/victim-application.component.ts +++ b/vsd-app/ClientApp/src/app/victim-application/victim-application.component.ts @@ -1,6 +1,18 @@ import { AEMService } from '../services/aem.service'; import { ActivatedRoute, Router } from '@angular/router'; -import { Application, Introduction, PersonalInformation, CrimeInformation, MedicalInformation, ExpenseInformation, EmploymentIncomeInformation, RepresentativeInformation, DeclarationInformation, AuthorizationInformation, DocumentCollectioninformation } from '../interfaces/application.interface'; +import { + Application, + Introduction, + PersonalInformation, + CrimeInformation, + MedicalInformation, + ExpenseInformation, + EmploymentIncomeInformation, + RepresentativeInformation, + DeclarationInformation, + AuthorizationInformation, + DocumentCollectioninformation +} from '../interfaces/application.interface'; import { ApplicationType, OnBehalfOf } from '../shared/enums-list'; import { AuthInfoHelper } from '../shared/authorization-information/authorization-information.helper'; import { CancelDialog } from '../shared/dialogs/cancel/cancel.dialog'; @@ -37,10 +49,9 @@ import * as _ from 'lodash'; providers: [ { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }, - { provide: STEPPER_GLOBAL_OPTIONS, useValue: { showError: true } }, - ], + { provide: STEPPER_GLOBAL_OPTIONS, useValue: { showError: true } } + ] }) - export class VictimApplicationComponent extends FormBase implements OnInit { @ViewChild('stepper') victimStepper: MatVerticalStepper; FORM_TYPE = ApplicationType.Victim_Application; @@ -75,7 +86,7 @@ export class VictimApplicationComponent extends FormBase implements OnInit { relationships: [], representativeRelationships: [], courts: [], - police_detachments: [], + police_detachments: [] }; constructor( @@ -87,7 +98,7 @@ export class VictimApplicationComponent extends FormBase implements OnInit { private matDialog: MatDialog, public state: StateService, public lookupService: LookupService, - private aemService: AEMService, + private aemService: AEMService ) { super(); } @@ -99,52 +110,61 @@ export class VictimApplicationComponent extends FormBase implements OnInit { if (this.state.cloning) { this.form = this.state.data; this.state.cloning = false; - } - else { + } else { this.form = this.buildApplicationForm(); } let promise_array = []; - promise_array.push(new Promise((resolve, reject) => { - this.lookupService.getCountries().subscribe((res) => { - this.lookupData.countries = res.value; - if (this.lookupData.countries) { - this.lookupData.countries.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); - } - resolve(); - }); - })); - - promise_array.push(new Promise((resolve, reject) => { - this.lookupService.getProvinces().subscribe((res) => { - this.lookupData.provinces = res.value; - if (this.lookupData.provinces) { - this.lookupData.provinces.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); - } - resolve(); - }); - })); - - promise_array.push(new Promise((resolve, reject) => { - this.lookupService.getCitiesByProvince(config.canada_crm_id, config.bc_crm_id).subscribe((res) => { - this.lookupData.cities = res.value; - if (this.lookupData.cities) { - this.lookupData.cities.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); - } - resolve(); - }); - })); + promise_array.push( + new Promise((resolve, reject) => { + this.lookupService.getCountries().subscribe((res) => { + this.lookupData.countries = res.value; + if (this.lookupData.countries) { + this.lookupData.countries.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); + } + resolve(); + }); + }) + ); + + promise_array.push( + new Promise((resolve, reject) => { + this.lookupService.getProvinces().subscribe((res) => { + this.lookupData.provinces = res.value; + if (this.lookupData.provinces) { + this.lookupData.provinces.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); + } + resolve(); + }); + }) + ); + + promise_array.push( + new Promise((resolve, reject) => { + this.lookupService.getCitiesByProvince(config.canada_crm_id, config.bc_crm_id).subscribe((res) => { + this.lookupData.cities = res.value; + if (this.lookupData.cities) { + this.lookupData.cities.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); + } + resolve(); + }); + }) + ); - promise_array.push(new Promise((resolve, reject) => { - this.lookupService.getRepresentativeRelationships().subscribe((res) => { - this.lookupData.representativeRelationships = res.value.filter(r => r.vsd_cvap_representativerelationship_imf_only != true); - if (this.lookupData.representativeRelationships) { - this.lookupData.representativeRelationships.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); - } - resolve(); - }); - })); + promise_array.push( + new Promise((resolve, reject) => { + this.lookupService.getRepresentativeRelationships().subscribe((res) => { + this.lookupData.representativeRelationships = res.value.filter( + (r) => r.vsd_cvap_representativerelationship_imf_only != true + ); + if (this.lookupData.representativeRelationships) { + this.lookupData.representativeRelationships.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); + } + resolve(); + }); + }) + ); Promise.all(promise_array).then((res) => { this.didLoad = true; @@ -152,7 +172,6 @@ export class VictimApplicationComponent extends FormBase implements OnInit { // console.log(this.lookupData); }); - if (completeOnBehalfOf) { this.form.get('representativeInformation').patchValue({ completingOnBehalfOf: parseInt(completeOnBehalfOf) @@ -172,15 +191,15 @@ export class VictimApplicationComponent extends FormBase implements OnInit { representativeInformation: this.representativeInfoHelper.setupFormGroup(this.fb, FORM), declarationInformation: this.declarationInfoHelper.setupFormGroup(this.fb, FORM), authorizationInformation: this.authInfoHelper.setupFormGroup(this.fb, FORM), - totalAttachmentSize: [0], + totalAttachmentSize: [0] }; if (FORM === ApplicationType.IFM_Application) { - group["victimInformation"] = this.victimInfoHelper.setupFormGroupForIfmApplication(this.fb); + group['victimInformation'] = this.victimInfoHelper.setupFormGroupForIfmApplication(this.fb); } if (FORM === ApplicationType.Victim_Application) { - group["employmentIncomeInformation"] = this.employmentInfoHelper.setupFormGroup(this.fb, FORM); + group['employmentIncomeInformation'] = this.employmentInfoHelper.setupFormGroup(this.fb, FORM); } return this.fb.group(group); @@ -193,7 +212,7 @@ export class VictimApplicationComponent extends FormBase implements OnInit { let self = this; let dialogRef = this.matDialog.open(CancelDialog, { autoFocus: false, - data: { type: "Application" } + data: { type: 'Application' } }); dialogRef.afterClosed().subscribe((res: any) => { @@ -212,7 +231,17 @@ export class VictimApplicationComponent extends FormBase implements OnInit { gotoNextStep(stepper: MatStepper, emptyPage?: boolean): void { // when a user clicks the continue button we move them to the next part of the form - let elements: Array = ['introduction', 'personalInformation', 'crimeInformation', 'medicalInformation', 'expenseInformation', 'employmentIncomeInformation', 'representativeInformation', 'declarationInformation', 'authorizationInformation']; + let elements: Array = [ + 'introduction', + 'personalInformation', + 'crimeInformation', + 'medicalInformation', + 'expenseInformation', + 'employmentIncomeInformation', + 'representativeInformation', + 'declarationInformation', + 'authorizationInformation' + ]; if (stepper != null) { // the stepper indexes match our form indexes @@ -233,7 +262,7 @@ export class VictimApplicationComponent extends FormBase implements OnInit { formValid = formParts.valid; // console.log(formParts); } else { - alert('That was a null form. Nothing to validate') + alert('That was a null form. Nothing to validate'); } // Ensure if the page is empty that the form is valid @@ -243,67 +272,73 @@ export class VictimApplicationComponent extends FormBase implements OnInit { //formParts.valid = true; } } - if (formValid) { - // console.log('Form is valid so proceeding to next step.') - this.showValidationMessage = false; - window.scroll(0, 0); - stepper.next(); - } else { - console.log('Form is not valid rerun the validation and show the validation message.') - this.validateAllFormFields(formParts); - this.showValidationMessage = true; - } + if (formValid) { + // console.log('Form is valid so proceeding to next step.') + this.showValidationMessage = false; + window.scroll(0, 0); + stepper.next(); + } else { + console.log('Form is not valid rerun the validation and show the validation message.'); + this.validateAllFormFields(formParts); + this.showValidationMessage = true; + } } } } downloadPDF() { - this.getAEMPDF().then((pdf: string) => { - let downloadLink = document.createElement("a"); - downloadLink.href = "data:application/pdf;base64," + pdf; - downloadLink.download = "Victim-Application.pdf"; - downloadLink.target = "_blank"; - - document.body.appendChild(downloadLink); - downloadLink.click(); - document.body.removeChild(downloadLink); - }).catch((err) => { - console.log("error getting pdf"); - console.log(err); - }); + this.getAEMPDF() + .then((pdf: string) => { + let downloadLink = document.createElement('a'); + downloadLink.href = 'data:application/pdf;base64,' + pdf; + downloadLink.download = 'Victim-Application.pdf'; + downloadLink.target = '_blank'; + + document.body.appendChild(downloadLink); + downloadLink.click(); + document.body.removeChild(downloadLink); + }) + .catch((err) => { + console.log('error getting pdf'); + console.log(err); + }); } getAEMPDF(): Promise { return new Promise((resolve, reject) => { let application: Application = _.cloneDeep(this.harvestForm()); //sending large document info to aem causes it to crap out - it's also unnecessary info, so let's not send it! - application.CrimeInformation.documents.forEach(doc => doc.body = ""); - application.EmploymentIncomeInformation.documents.forEach(doc => doc.body = ""); - application.RepresentativeInformation.documents.forEach(doc => doc.body = ""); - + application.CrimeInformation.documents.forEach((doc) => (doc.body = '')); + application.EmploymentIncomeInformation.documents.forEach((doc) => (doc.body = '')); + application.RepresentativeInformation.documents.forEach((doc) => (doc.body = '')); //full name display option for single fields - application.PersonalInformation.fullName = application.PersonalInformation.firstName + " " + application.PersonalInformation.lastName; + application.PersonalInformation.fullName = + application.PersonalInformation.firstName + ' ' + application.PersonalInformation.lastName; //display all locations as a single comma separated string - application.CrimeInformation.crimeLocations[0].location = application.CrimeInformation.crimeLocations.map(a => a.location).join(', '); + application.CrimeInformation.crimeLocations[0].location = application.CrimeInformation.crimeLocations + .map((a) => a.location) + .join(', '); //for on behalf of, if you chose parent, pdf format doesn't match webform, so relationship workaround if (application.RepresentativeInformation.completingOnBehalfOf == OnBehalfOf.Parent) { - application.RepresentativeInformation.relationshipToPersonParent = application.RepresentativeInformation.relationshipToPerson; - application.RepresentativeInformation.relationshipToPerson = ""; + application.RepresentativeInformation.relationshipToPersonParent = + application.RepresentativeInformation.relationshipToPerson; + application.RepresentativeInformation.relationshipToPerson = ''; } - this.aemService.getVictimApplicationPDF(application).subscribe((res: any) => { - console.log(res); - if (res.responseMessage) { - resolve(res.responseMessage); - } - else { - reject(res); - } - }, + this.aemService.getVictimApplicationPDF(application).subscribe( + (res: any) => { + console.log(res); + if (res.responseMessage) { + resolve(res.responseMessage); + } else { + reject(res); + } + }, (err) => { reject(err); console.log(err); - }); + } + ); }); } @@ -311,24 +346,26 @@ export class VictimApplicationComponent extends FormBase implements OnInit { return new Promise((resolve, reject) => { let application: Application = _.cloneDeep(this.harvestForm()); //sending large document info to aem causes it to crap out - it's also unnecessary info, so let's not send it! - application.CrimeInformation.documents.forEach(doc => doc.body = ""); - application.EmploymentIncomeInformation.documents.forEach(doc => doc.body = ""); - application.RepresentativeInformation.documents.forEach(doc => doc.body = ""); + application.CrimeInformation.documents.forEach((doc) => (doc.body = '')); + application.EmploymentIncomeInformation.documents.forEach((doc) => (doc.body = '')); + application.RepresentativeInformation.documents.forEach((doc) => (doc.body = '')); //full name display option for single fields - application.PersonalInformation.fullName = application.PersonalInformation.firstName + " " + application.PersonalInformation.lastName; - this.aemService.getAuthorizationPDF(application).subscribe((res: any) => { - console.log(res); - if (res.responseMessage) { - resolve(res.responseMessage); - } - else { - reject(res); - } - }, + application.PersonalInformation.fullName = + application.PersonalInformation.firstName + ' ' + application.PersonalInformation.lastName; + this.aemService.getAuthorizationPDF(application).subscribe( + (res: any) => { + console.log(res); + if (res.responseMessage) { + resolve(res.responseMessage); + } else { + reject(res); + } + }, (err) => { reject(err); console.log(err); - }); + } + ); }); } @@ -337,47 +374,57 @@ export class VictimApplicationComponent extends FormBase implements OnInit { let ret: DocumentCollectioninformation[] = []; let promise_array = []; - promise_array.push(new Promise((resolve, reject) => { - this.getAEMPDF().then((pdf: string) => { - ret.push({ - body: pdf, - filename: "Victim-Application.pdf", - subject: "", - }); - resolve(); - }).catch((err) => { - console.log(err); - reject(); - }); - })); - - promise_array.push(new Promise((resolve, reject) => { - this.getAuthPDF().then((auth_pdf: string) => { - ret.push({ - body: auth_pdf, - filename: "Authorization Form.pdf", - subject: "", - }); - resolve(); - }).catch((err) => { + promise_array.push( + new Promise((resolve, reject) => { + this.getAEMPDF() + .then((pdf: string) => { + ret.push({ + body: pdf, + filename: 'Victim-Application.pdf', + subject: '' + }); + resolve(); + }) + .catch((err) => { + console.log(err); + reject(); + }); + }) + ); + + promise_array.push( + new Promise((resolve, reject) => { + this.getAuthPDF() + .then((auth_pdf: string) => { + ret.push({ + body: auth_pdf, + filename: 'Authorization Form.pdf', + subject: '' + }); + resolve(); + }) + .catch((err) => { + console.log(err); + reject(); + }); + }) + ); + + Promise.all(promise_array) + .then((res) => { + resolve(ret); + }) + .catch((err) => { console.log(err); - reject(); + reject(err); }); - })); - - Promise.all(promise_array).then((res) => { - resolve(ret); - }).catch((err) => { - console.log(err); - reject(err); - }); }); } printApplication() { window.scroll(0, 0); this.showPrintView = true; - document.querySelectorAll(".slide-close")[0].classList.add("hide-for-print"); + document.querySelectorAll('.slide-close')[0].classList.add('hide-for-print'); setTimeout(() => { window.print(); }, 100); @@ -385,57 +432,69 @@ export class VictimApplicationComponent extends FormBase implements OnInit { @HostListener('window:afterprint') onafterprint() { - document.querySelectorAll(".slide-close")[0].classList.remove("hide-for-print") + document.querySelectorAll('.slide-close')[0].classList.remove('hide-for-print'); window.scroll(0, 0); this.showPrintView = false; } submitApplication() { this.submitting = true; - if ((this.form.valid) || (this.form.controls.personalInformation.valid // It's OK if this.form.controls.employmentIncomeInformation.valid is not valid - && this.form.controls.crimeInformation.valid - && this.form.controls.declarationInformation.valid - && this.form.controls.expenseInformation.valid - && this.form.controls.introduction.valid - && this.form.controls.medicalInformation.valid - && this.form.controls.personalInformation.valid - && this.form.controls.representativeInformation.valid)) { - this.getApplicationPDFs().then((pdfs: DocumentCollectioninformation[]) => { - let form = this.harvestForm(); - form.ApplicationPDFs = pdfs; - this.justiceDataService.submitApplication(form) - .subscribe( - data => { + if ( + this.form.valid || + (this.form.controls.personalInformation.valid && // It's OK if this.form.controls.employmentIncomeInformation.valid is not valid + this.form.controls.crimeInformation.valid && + this.form.controls.declarationInformation.valid && + this.form.controls.expenseInformation.valid && + this.form.controls.introduction.valid && + this.form.controls.medicalInformation.valid && + this.form.controls.personalInformation.valid && + this.form.controls.representativeInformation.valid) + ) { + this.getApplicationPDFs() + .then((pdfs: DocumentCollectioninformation[]) => { + let form = this.harvestForm(); + form.ApplicationPDFs = pdfs; + this.justiceDataService.submitApplication(form).subscribe( + (data) => { if (data['IsSuccess'] == true) { this.router.navigate(['/application-success']); - } - else { + } else { this.submitting = false; - this.snackBar.open('Error submitting application. ' + data['message'], 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); + this.snackBar.open('Error submitting application. ' + data['message'], 'Fail', { + duration: 3500, + panelClass: ['red-snackbar'] + }); console.log('Error submitting application. ' + data['message']); if (this.isIE) { - alert("Encountered an error. Please use another browser as this may resolve the problem.") + alert('Encountered an error. Please use another browser as this may resolve the problem.'); } } }, - error => { + (error) => { this.submitting = false; - this.snackBar.open('Error submitting application', 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); + this.snackBar.open('Error submitting application', 'Fail', { + duration: 3500, + panelClass: ['red-snackbar'] + }); console.log('Error submitting application'); if (this.isIE) { - alert("Encountered an error. Please use another browser as this may resolve the problem.") + alert('Encountered an error. Please use another browser as this may resolve the problem.'); } } ); - }).catch((err) => { - this.submitting = false; - this.snackBar.open('Error submitting application. ', 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); - console.log('Error submitting application. Problem getting AEM pdfs...'); - console.log(err); - }); + }) + .catch((err) => { + this.submitting = false; + this.snackBar.open('Error submitting application. ', 'Fail', { + duration: 3500, + panelClass: ['red-snackbar'] + }); + console.log('Error submitting application. Problem getting AEM pdfs...'); + console.log(err); + }); } else { this.submitting = false; - console.log("form not validated"); + console.log('form not validated'); this.markAsTouched(); } } @@ -444,21 +503,20 @@ export class VictimApplicationComponent extends FormBase implements OnInit { this.submitting = true; if (this.form.valid) { let thisForm = _.cloneDeep(this.form); - this.getApplicationPDFs().then((pdfs: DocumentCollectioninformation[]) => { - let form = this.harvestForm(); - form.ApplicationPDFs = pdfs; - this.justiceDataService.submitApplication(form) - .subscribe( - data => { + this.getApplicationPDFs() + .then((pdfs: DocumentCollectioninformation[]) => { + let form = this.harvestForm(); + form.ApplicationPDFs = pdfs; + this.justiceDataService.submitApplication(form).subscribe( + (data) => { if (data['IsSuccess'] == true) { - if (type === "VICTIM") { + if (type === 'VICTIM') { this.submitting = false; let victimForm = this.cloneFormToVictim(thisForm); this.victimStepper.reset(); this.form = victimForm; - } - else if (type === "IFM") { + } else if (type === 'IFM') { this.submitting = false; let ifmForm = this.cloneFormToIFM(thisForm); @@ -466,38 +524,46 @@ export class VictimApplicationComponent extends FormBase implements OnInit { this.state.data = ifmForm; this.router.navigate(['/ifm-application']); - } - else { + } else { this.router.navigate(['/application-success']); } - } - else { + } else { this.submitting = false; - this.snackBar.open('Error submitting application. ' + data['message'], 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); + this.snackBar.open('Error submitting application. ' + data['message'], 'Fail', { + duration: 3500, + panelClass: ['red-snackbar'] + }); console.log('Error submitting application. ' + data['message']); if (this.isIE) { - alert("Encountered an error. Please use another browser as this may resolve the problem.") + alert('Encountered an error. Please use another browser as this may resolve the problem.'); } } }, - error => { + (error) => { this.submitting = false; - this.snackBar.open('Error submitting application', 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); + this.snackBar.open('Error submitting application', 'Fail', { + duration: 3500, + panelClass: ['red-snackbar'] + }); console.log('Error submitting application'); if (this.isIE) { - alert("Encountered an error. Please use another browser as this may resolve the problem.") + alert('Encountered an error. Please use another browser as this may resolve the problem.'); } } ); - }).catch((err) => { - this.submitting = false; - this.snackBar.open('Error submitting application. ', 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); - console.log('Error submitting application. Problem getting AEM pdfs...'); - console.log(err); - }) + }) + .catch((err) => { + this.submitting = false; + this.snackBar.open('Error submitting application. ', 'Fail', { + duration: 3500, + panelClass: ['red-snackbar'] + }); + console.log('Error submitting application. Problem getting AEM pdfs...'); + console.log(err); + }); } else { this.submitting = false; - console.log("form not validated"); + console.log('form not validated'); this.markAsTouched(); } } @@ -515,7 +581,7 @@ export class VictimApplicationComponent extends FormBase implements OnInit { EmploymentIncomeInformation: this.form.get('employmentIncomeInformation').value as EmploymentIncomeInformation, RepresentativeInformation: this.form.get('representativeInformation').value as RepresentativeInformation, DeclarationInformation: this.form.get('declarationInformation').value as DeclarationInformation, - AuthorizationInformation: this.form.get('authorizationInformation').value as AuthorizationInformation, + AuthorizationInformation: this.form.get('authorizationInformation').value as AuthorizationInformation } as Application; //using this as a workaround to collect values from disabled fields @@ -526,13 +592,11 @@ export class VictimApplicationComponent extends FormBase implements OnInit { return data; } - save(): void { - this.justiceDataService.submitApplication(this.harvestForm()) - .subscribe( - data => { }, - err => { } - ); + this.justiceDataService.submitApplication(this.harvestForm()).subscribe( + (data) => {}, + (err) => {} + ); } markAsTouched() { @@ -582,7 +646,10 @@ export class VictimApplicationComponent extends FormBase implements OnInit { ret.get('crimeInformation').get('offenderRelationship').patchValue(''); ret.get('crimeInformation').get('haveYouSuedOffender').patchValue(0); ret.get('crimeInformation').get('intendToSueOffender').patchValue(null); - ret.get('crimeInformation').get('racafInformation').patchValue(this.crimeInfoHelper.createRACAFInformation(this.fb).value); + ret + .get('crimeInformation') + .get('racafInformation') + .patchValue(this.crimeInfoHelper.createRACAFInformation(this.fb).value); let authorizedPersonsLength = currentForm.get('authorizationInformation').get('authorizedPerson').value.length; let authorizedPersons = ret.get('authorizationInformation').get('authorizedPerson') as FormArray; @@ -606,18 +673,51 @@ export class VictimApplicationComponent extends FormBase implements OnInit { // console.log(currentForm); let ret = this.buildApplicationForm(ApplicationType.IFM_Application); - ret.get('personalInformation').get('preferredMethodOfContact').patchValue(currentForm.get('personalInformation').get('preferredMethodOfContact').value); - ret.get('personalInformation').get('permissionToContactViaMethod').patchValue(currentForm.get('personalInformation').get('permissionToContactViaMethod').value); - ret.get('personalInformation').get('agreeToCvapCommunicationExchange').patchValue(currentForm.get('personalInformation').get('agreeToCvapCommunicationExchange').value); - ret.get('personalInformation').get('phoneNumber').patchValue(currentForm.get('personalInformation').get('phoneNumber').value); - ret.get('personalInformation').get('leaveVoicemail').patchValue(currentForm.get('personalInformation').get('leaveVoicemail').value); - ret.get('personalInformation').get('alternatePhoneNumber').patchValue(currentForm.get('personalInformation').get('alternatePhoneNumber').value); + ret + .get('personalInformation') + .get('preferredMethodOfContact') + .patchValue(currentForm.get('personalInformation').get('preferredMethodOfContact').value); + ret + .get('personalInformation') + .get('permissionToContactViaMethod') + .patchValue(currentForm.get('personalInformation').get('permissionToContactViaMethod').value); + ret + .get('personalInformation') + .get('agreeToCvapCommunicationExchange') + .patchValue(currentForm.get('personalInformation').get('agreeToCvapCommunicationExchange').value); + ret + .get('personalInformation') + .get('phoneNumber') + .patchValue(currentForm.get('personalInformation').get('phoneNumber').value); + ret + .get('personalInformation') + .get('leaveVoicemail') + .patchValue(currentForm.get('personalInformation').get('leaveVoicemail').value); + ret + .get('personalInformation') + .get('alternatePhoneNumber') + .patchValue(currentForm.get('personalInformation').get('alternatePhoneNumber').value); ret.get('personalInformation').get('email').patchValue(currentForm.get('personalInformation').get('email').value); - ret.get('personalInformation').get('confirmEmail').patchValue(currentForm.get('personalInformation').get('confirmEmail').value); - ret.get('personalInformation').get('doNotLiveAtAddress').patchValue(currentForm.get('personalInformation').get('doNotLiveAtAddress').value); - ret.get('personalInformation').get('mailRecipient').patchValue(currentForm.get('personalInformation').get('mailRecipient').value); - ret.get('personalInformation').get('primaryAddress').patchValue(currentForm.get('personalInformation').get('primaryAddress').value); - ret.get('personalInformation').get('alternateAddress').patchValue(currentForm.get('personalInformation').get('alternateAddress').value); + ret + .get('personalInformation') + .get('confirmEmail') + .patchValue(currentForm.get('personalInformation').get('confirmEmail').value); + ret + .get('personalInformation') + .get('doNotLiveAtAddress') + .patchValue(currentForm.get('personalInformation').get('doNotLiveAtAddress').value); + ret + .get('personalInformation') + .get('mailRecipient') + .patchValue(currentForm.get('personalInformation').get('mailRecipient').value); + ret + .get('personalInformation') + .get('primaryAddress') + .patchValue(currentForm.get('personalInformation').get('primaryAddress').value); + ret + .get('personalInformation') + .get('alternateAddress') + .patchValue(currentForm.get('personalInformation').get('alternateAddress').value); ret.get('victimInformation').patchValue(currentForm.get('personalInformation').value); @@ -645,7 +745,10 @@ export class VictimApplicationComponent extends FormBase implements OnInit { ret.get('crimeInformation').get('offenderRelationship').patchValue(''); ret.get('crimeInformation').get('haveYouSuedOffender').patchValue(0); ret.get('crimeInformation').get('intendToSueOffender').patchValue(null); - ret.get('crimeInformation').get('racafInformation').patchValue(this.crimeInfoHelper.createRACAFInformation(this.fb).value); + ret + .get('crimeInformation') + .get('racafInformation') + .patchValue(this.crimeInfoHelper.createRACAFInformation(this.fb).value); let authorizedPersonsLength = currentForm.get('authorizationInformation').get('authorizedPerson').value.length; let authorizedPersons = ret.get('authorizationInformation').get('authorizedPerson') as FormArray; diff --git a/vsd-app/ClientApp/src/app/witness-application/witness-application.component.spec.ts b/vsd-app/ClientApp/src/app/witness-application/witness-application.component.spec.ts index d8c8a2a2..78622c92 100644 --- a/vsd-app/ClientApp/src/app/witness-application/witness-application.component.spec.ts +++ b/vsd-app/ClientApp/src/app/witness-application/witness-application.component.spec.ts @@ -1,23 +1,21 @@ import { TestBed, async, ComponentFixture, ComponentFixtureAutoDetect } from '@angular/core/testing'; -import { BrowserModule, By } from "@angular/platform-browser"; +import { BrowserModule, By } from '@angular/platform-browser'; import { WitnessApplicationComponent } from './witness-application.component'; let component: WitnessApplicationComponent; let fixture: ComponentFixture; describe('WitnessApplication component', () => { - beforeEach(async(() => { - TestBed.configureTestingModule({ - declarations: [ WitnessApplicationComponent ], - imports: [ BrowserModule ], - providers: [ - { provide: ComponentFixtureAutoDetect, useValue: true } - ] - }); - fixture = TestBed.createComponent(WitnessApplicationComponent); - component = fixture.componentInstance; - })); + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [WitnessApplicationComponent], + imports: [BrowserModule], + providers: [{ provide: ComponentFixtureAutoDetect, useValue: true }] + }); + fixture = TestBed.createComponent(WitnessApplicationComponent); + component = fixture.componentInstance; + })); - it('should do something', async(() => { - expect(true).toEqual(true); - })); + it('should do something', async(() => { + expect(true).toEqual(true); + })); }); diff --git a/vsd-app/ClientApp/src/app/witness-application/witness-application.component.ts b/vsd-app/ClientApp/src/app/witness-application/witness-application.component.ts index 9722fc23..b843433c 100644 --- a/vsd-app/ClientApp/src/app/witness-application/witness-application.component.ts +++ b/vsd-app/ClientApp/src/app/witness-application/witness-application.component.ts @@ -1,6 +1,19 @@ import { AEMService } from '../services/aem.service'; import { ActivatedRoute, Router } from '@angular/router'; -import { Application, Introduction, PersonalInformation, CrimeInformation, MedicalInformation, ExpenseInformation, EmploymentIncomeInformation, RepresentativeInformation, DeclarationInformation, AuthorizationInformation, VictimInformation, DocumentCollectioninformation } from '../interfaces/application.interface'; +import { + Application, + Introduction, + PersonalInformation, + CrimeInformation, + MedicalInformation, + ExpenseInformation, + EmploymentIncomeInformation, + RepresentativeInformation, + DeclarationInformation, + AuthorizationInformation, + VictimInformation, + DocumentCollectioninformation +} from '../interfaces/application.interface'; import { ApplicationType, OnBehalfOf } from '../shared/enums-list'; import { AuthInfoHelper } from '../shared/authorization-information/authorization-information.helper'; import { CancelDialog } from '../shared/dialogs/cancel/cancel.dialog'; @@ -41,10 +54,9 @@ const moment = _rollupMoment || _moment; // our example generation script. { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }, - { provide: STEPPER_GLOBAL_OPTIONS, useValue: { showError: true } }, - ], + { provide: STEPPER_GLOBAL_OPTIONS, useValue: { showError: true } } + ] }) - export class WitnessApplicationComponent extends FormBase implements OnInit { FORM_TYPE: ApplicationType = ApplicationType.Witness_Application; busy: Promise; @@ -78,7 +90,7 @@ export class WitnessApplicationComponent extends FormBase implements OnInit { relationships: [], representativeRelationships: [], courts: [], - police_detachments: [], + police_detachments: [] }; constructor( @@ -89,7 +101,7 @@ export class WitnessApplicationComponent extends FormBase implements OnInit { public snackBar: MatSnackBar, private dialog: MatDialog, public lookupService: LookupService, - private aemService: AEMService, + private aemService: AEMService ) { super(); this.formFullyValidated = false; @@ -105,45 +117,53 @@ export class WitnessApplicationComponent extends FormBase implements OnInit { let promise_array = []; - promise_array.push(new Promise((resolve, reject) => { - this.lookupService.getCountries().subscribe((res) => { - this.lookupData.countries = res.value; - if (this.lookupData.countries) { - this.lookupData.countries.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); - } - resolve(); - }); - })); - - promise_array.push(new Promise((resolve, reject) => { - this.lookupService.getProvinces().subscribe((res) => { - this.lookupData.provinces = res.value; - if (this.lookupData.provinces) { - this.lookupData.provinces.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); - } - resolve(); - }); - })); - - promise_array.push(new Promise((resolve, reject) => { - this.lookupService.getCitiesByProvince(config.canada_crm_id, config.bc_crm_id).subscribe((res) => { - this.lookupData.cities = res.value; - if (this.lookupData.cities) { - this.lookupData.cities.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); - } - resolve(); - }); - })); - - promise_array.push(new Promise((resolve, reject) => { - this.lookupService.getRepresentativeRelationships().subscribe((res) => { - this.lookupData.representativeRelationships = res.value; - if (this.lookupData.representativeRelationships) { - this.lookupData.representativeRelationships.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); - } - resolve(); - }); - })); + promise_array.push( + new Promise((resolve, reject) => { + this.lookupService.getCountries().subscribe((res) => { + this.lookupData.countries = res.value; + if (this.lookupData.countries) { + this.lookupData.countries.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); + } + resolve(); + }); + }) + ); + + promise_array.push( + new Promise((resolve, reject) => { + this.lookupService.getProvinces().subscribe((res) => { + this.lookupData.provinces = res.value; + if (this.lookupData.provinces) { + this.lookupData.provinces.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); + } + resolve(); + }); + }) + ); + + promise_array.push( + new Promise((resolve, reject) => { + this.lookupService.getCitiesByProvince(config.canada_crm_id, config.bc_crm_id).subscribe((res) => { + this.lookupData.cities = res.value; + if (this.lookupData.cities) { + this.lookupData.cities.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); + } + resolve(); + }); + }) + ); + + promise_array.push( + new Promise((resolve, reject) => { + this.lookupService.getRepresentativeRelationships().subscribe((res) => { + this.lookupData.representativeRelationships = res.value; + if (this.lookupData.representativeRelationships) { + this.lookupData.representativeRelationships.sort((a, b) => a.vsd_name.localeCompare(b.vsd_name)); + } + resolve(); + }); + }) + ); Promise.all(promise_array).then((res) => { this.didLoad = true; @@ -162,7 +182,7 @@ export class WitnessApplicationComponent extends FormBase implements OnInit { let self = this; let dialogRef = this.dialog.open(CancelDialog, { autoFocus: false, - data: { type: "Application" } + data: { type: 'Application' } }); dialogRef.afterClosed().subscribe((res: any) => { @@ -177,7 +197,17 @@ export class WitnessApplicationComponent extends FormBase implements OnInit { } getFormGroupName(groupIndex: any) { - let elements: Array = ['introduction', 'personalInformation', 'victimInformation', 'crimeInformation', 'medicalInformation', 'expenseInformation', 'representativeInformation', 'declarationInformation', 'authorizationInformation']; + let elements: Array = [ + 'introduction', + 'personalInformation', + 'victimInformation', + 'crimeInformation', + 'medicalInformation', + 'expenseInformation', + 'representativeInformation', + 'declarationInformation', + 'authorizationInformation' + ]; return elements[groupIndex]; } @@ -217,42 +247,51 @@ export class WitnessApplicationComponent extends FormBase implements OnInit { submitApplication() { this.submitting = true; if (this.form.valid) { - this.getApplicationPDFs().then((pdfs: DocumentCollectioninformation[]) => { - let form = this.harvestForm(); - form.ApplicationPDFs = pdfs; - this.justiceDataService.submitApplication(form) - .subscribe( - data => { + this.getApplicationPDFs() + .then((pdfs: DocumentCollectioninformation[]) => { + let form = this.harvestForm(); + form.ApplicationPDFs = pdfs; + this.justiceDataService.submitApplication(form).subscribe( + (data) => { if (data['IsSuccess'] == true) { this.router.navigate(['/application-success']); - } - else { + } else { this.submitting = false; - this.snackBar.open('Error submitting application', 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); + this.snackBar.open('Error submitting application', 'Fail', { + duration: 3500, + panelClass: ['red-snackbar'] + }); console.log('Error submitting application'); if (this.isIE) { - alert("Encountered an error. Please use another browser as this may resolve the problem.") + alert('Encountered an error. Please use another browser as this may resolve the problem.'); } } }, - error => { + (error) => { this.submitting = false; - this.snackBar.open('Error submitting application', 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); + this.snackBar.open('Error submitting application', 'Fail', { + duration: 3500, + panelClass: ['red-snackbar'] + }); console.log('Error submitting application'); if (this.isIE) { - alert("Encountered an error. Please use another browser as this may resolve the problem.") + alert('Encountered an error. Please use another browser as this may resolve the problem.'); } } ); - }).catch((err) => { - this.submitting = false; - this.snackBar.open('Error submitting application. ', 'Fail', { duration: 3500, panelClass: ['red-snackbar'] }); - console.log('Error submitting application. Problem getting AEM pdfs...'); - console.log(err); - }); + }) + .catch((err) => { + this.submitting = false; + this.snackBar.open('Error submitting application. ', 'Fail', { + duration: 3500, + panelClass: ['red-snackbar'] + }); + console.log('Error submitting application. Problem getting AEM pdfs...'); + console.log(err); + }); } else { this.submitting = false; - console.log("form not validated"); + console.log('form not validated'); this.markAsTouched(); } } @@ -271,7 +310,7 @@ export class WitnessApplicationComponent extends FormBase implements OnInit { RepresentativeInformation: this.form.get('representativeInformation').value as RepresentativeInformation, DeclarationInformation: this.form.get('declarationInformation').value as DeclarationInformation, AuthorizationInformation: this.form.get('authorizationInformation').value as AuthorizationInformation, - VictimInformation: this.form.get('victimInformation').value as VictimInformation, + VictimInformation: this.form.get('victimInformation').value as VictimInformation } as Application; //using this as a workaround to collect values from disabled fields @@ -307,61 +346,68 @@ export class WitnessApplicationComponent extends FormBase implements OnInit { representativeInformation: this.representativeInfoHelper.setupFormGroup(this.fb, this.FORM_TYPE), declarationInformation: this.declarationInfoHelper.setupFormGroup(this.fb, this.FORM_TYPE), authorizationInformation: this.authInfoHelper.setupFormGroup(this.fb, this.FORM_TYPE), - totalAttachmentSize: [0], + totalAttachmentSize: [0] }); } @HostListener('window:afterprint') onafterprint() { - document.querySelectorAll(".slide-close")[0].classList.remove("hide-for-print") + document.querySelectorAll('.slide-close')[0].classList.remove('hide-for-print'); window.scroll(0, 0); this.showPrintView = false; } downloadPDF() { - this.getAEMPDF().then((pdf: string) => { - let downloadLink = document.createElement("a"); - downloadLink.href = "data:application/pdf;base64," + pdf; - downloadLink.download = "Witness-Application.pdf"; - downloadLink.target = "_blank"; - - document.body.appendChild(downloadLink); - downloadLink.click(); - document.body.removeChild(downloadLink); - }).catch((err) => { - console.log("error getting pdf"); - console.log(err); - }); + this.getAEMPDF() + .then((pdf: string) => { + let downloadLink = document.createElement('a'); + downloadLink.href = 'data:application/pdf;base64,' + pdf; + downloadLink.download = 'Witness-Application.pdf'; + downloadLink.target = '_blank'; + + document.body.appendChild(downloadLink); + downloadLink.click(); + document.body.removeChild(downloadLink); + }) + .catch((err) => { + console.log('error getting pdf'); + console.log(err); + }); } getAEMPDF(): Promise { return new Promise((resolve, reject) => { let application: Application = _.cloneDeep(this.harvestForm()); //sending large document info to aem causes it to crap out - it's also unnecessary info, so let's not send it! - application.CrimeInformation.documents.forEach(doc => doc.body = ""); - application.RepresentativeInformation.documents.forEach(doc => doc.body = ""); + application.CrimeInformation.documents.forEach((doc) => (doc.body = '')); + application.RepresentativeInformation.documents.forEach((doc) => (doc.body = '')); //full name display option for single fields - application.PersonalInformation.fullName = application.PersonalInformation.firstName + " " + application.PersonalInformation.lastName; + application.PersonalInformation.fullName = + application.PersonalInformation.firstName + ' ' + application.PersonalInformation.lastName; //display all locations as a single comma separated string - application.CrimeInformation.crimeLocations[0].location = application.CrimeInformation.crimeLocations.map(a => a.location).join(', '); + application.CrimeInformation.crimeLocations[0].location = application.CrimeInformation.crimeLocations + .map((a) => a.location) + .join(', '); //for on behalf of, if you chose parent, pdf format doesn't match webform, so relationship workaround if (application.RepresentativeInformation.completingOnBehalfOf == OnBehalfOf.Parent) { - application.RepresentativeInformation.relationshipToPersonParent = application.RepresentativeInformation.relationshipToPerson; - application.RepresentativeInformation.relationshipToPerson = ""; + application.RepresentativeInformation.relationshipToPersonParent = + application.RepresentativeInformation.relationshipToPerson; + application.RepresentativeInformation.relationshipToPerson = ''; } - this.aemService.getWitnessApplicationPDF(application).subscribe((res: any) => { - console.log(res); - if (res.responseMessage) { - resolve(res.responseMessage); - } - else { - reject(res); - } - }, + this.aemService.getWitnessApplicationPDF(application).subscribe( + (res: any) => { + console.log(res); + if (res.responseMessage) { + resolve(res.responseMessage); + } else { + reject(res); + } + }, (err) => { reject(err); console.log(err); - }); + } + ); }); } @@ -369,23 +415,25 @@ export class WitnessApplicationComponent extends FormBase implements OnInit { return new Promise((resolve, reject) => { let application: Application = _.cloneDeep(this.harvestForm()); //sending large document info to aem causes it to crap out - it's also unnecessary info, so let's not send it! - application.CrimeInformation.documents.forEach(doc => doc.body = ""); - application.RepresentativeInformation.documents.forEach(doc => doc.body = ""); + application.CrimeInformation.documents.forEach((doc) => (doc.body = '')); + application.RepresentativeInformation.documents.forEach((doc) => (doc.body = '')); //full name display option for single fields - application.PersonalInformation.fullName = application.PersonalInformation.firstName + " " + application.PersonalInformation.lastName; - this.aemService.getAuthorizationPDF(application).subscribe((res: any) => { - console.log(res); - if (res.responseMessage) { - resolve(res.responseMessage); - } - else { - reject(res); - } - }, + application.PersonalInformation.fullName = + application.PersonalInformation.firstName + ' ' + application.PersonalInformation.lastName; + this.aemService.getAuthorizationPDF(application).subscribe( + (res: any) => { + console.log(res); + if (res.responseMessage) { + resolve(res.responseMessage); + } else { + reject(res); + } + }, (err) => { reject(err); console.log(err); - }); + } + ); }); } @@ -394,47 +442,57 @@ export class WitnessApplicationComponent extends FormBase implements OnInit { let ret: DocumentCollectioninformation[] = []; let promise_array = []; - promise_array.push(new Promise((resolve, reject) => { - this.getAEMPDF().then((pdf: string) => { - ret.push({ - body: pdf, - filename: "Witness-Application.pdf", - subject: "", - }); - resolve(); - }).catch((err) => { + promise_array.push( + new Promise((resolve, reject) => { + this.getAEMPDF() + .then((pdf: string) => { + ret.push({ + body: pdf, + filename: 'Witness-Application.pdf', + subject: '' + }); + resolve(); + }) + .catch((err) => { + console.log(err); + reject(); + }); + }) + ); + + promise_array.push( + new Promise((resolve, reject) => { + this.getAuthPDF() + .then((auth_pdf: string) => { + ret.push({ + body: auth_pdf, + filename: 'Authorization Form.pdf', + subject: '' + }); + resolve(); + }) + .catch((err) => { + console.log(err); + reject(); + }); + }) + ); + + Promise.all(promise_array) + .then((res) => { + resolve(ret); + }) + .catch((err) => { console.log(err); - reject(); - }); - })); - - promise_array.push(new Promise((resolve, reject) => { - this.getAuthPDF().then((auth_pdf: string) => { - ret.push({ - body: auth_pdf, - filename: "Authorization Form.pdf", - subject: "", - }); - resolve(); - }).catch((err) => { - console.log(err); - reject(); + reject(err); }); - })); - - Promise.all(promise_array).then((res) => { - resolve(ret); - }).catch((err) => { - console.log(err); - reject(err); - }); }); } printApplication() { window.scroll(0, 0); this.showPrintView = true; - document.querySelectorAll(".slide-close")[0].classList.add("hide-for-print"); + document.querySelectorAll('.slide-close')[0].classList.add('hide-for-print'); setTimeout(() => { window.print(); }, 100); diff --git a/vsd-app/ClientApp/src/config.ts b/vsd-app/ClientApp/src/config.ts index 7f234a03..37f798fe 100644 --- a/vsd-app/ClientApp/src/config.ts +++ b/vsd-app/ClientApp/src/config.ts @@ -1,50 +1,45 @@ export const config = { - canada_crm_id: "52e224c4-989a-e811-8155-480fcff4f6a1", - bc_crm_id: "fde4dbca-989a-e811-8155-480fcff4f6a1", - preferred_police_detachments: [ - { vsd_name: "Surrey RCMP Detachment", vsd_policedetachmentid: "7e9e3177-b5a4-e811-8164-480fcff407a1" }, - { vsd_name: "Vancouver Police Department", vsd_policedetachmentid: "369f3177-b5a4-e811-8164-480fcff407a1" }, - { vsd_name: "Abbotsford Police Department", vsd_policedetachmentid: "1c9e3177-b5a4-e811-8164-480fcff407a1" }, - { vsd_name: "Kelowna RCMP Detachment", vsd_policedetachmentid: "b89d3177-b5a4-e811-8164-480fcff407a1" }, - { vsd_name: "Chilliwack RCMP Detachment", vsd_policedetachmentid: "429f3177-b5a4-e811-8164-480fcff407a1" }, - { vsd_name: "New Westminster Police Department", vsd_policedetachmentid: "269e3177-b5a4-e811-8164-480fcff407a1" }, - { vsd_name: "Burnaby RCMP Detachment", vsd_policedetachmentid: "b8cf9469-ada4-e811-815f-480fcff4f621" }, - { vsd_name: "Victoria Police Department", vsd_policedetachmentid: "169e3177-b5a4-e811-8164-480fcff407a1" }, - { vsd_name: "Coquitlam RCMP Detachment", vsd_policedetachmentid: "709e3177-b5a4-e811-8164-480fcff407a1" }, - { vsd_name: "Langley RCMP Detachment", vsd_policedetachmentid: "749e3177-b5a4-e811-8164-480fcff407a1" }, - { vsd_name: "Nanaimo RCMP Detachment", vsd_policedetachmentid: "949e3177-b5a4-e811-8164-480fcff407a1" }, - { vsd_name: "Kamloops RCMP Detachment", vsd_policedetachmentid: "e09d3177-b5a4-e811-8164-480fcff407a1" } - ], - - preferred_countries: [ - { vsd_name: "Other", vsd_countryid: "" }, - { vsd_name: "Canada", vsd_countryid: "52e224c4-989a-e811-8155-480fcff4f6a1" }, - { vsd_name: "United States of America", vsd_countryid: "49b05a13-e149-ea11-b816-00505683fbf4" }, - { vsd_name: "Mexico", vsd_countryid: "39b05a13-e149-ea11-b816-00505683fbf4" }, - { vsd_name: "United Kingdom", vsd_countryid: "55b05a13-e149-ea11-b816-00505683fbf4" }, - { vsd_name: "Australia", vsd_countryid: "11b05a13-e149-ea11-b816-00505683fbf4" }, - { vsd_name: "India", vsd_countryid: "2db05a13-e149-ea11-b816-00505683fbf4" }, - { vsd_name: "Italy", vsd_countryid: "31b05a13-e149-ea11-b816-00505683fbf4" }, - { vsd_name: "China", vsd_countryid: "15b05a13-e149-ea11-b816-00505683fbf4" }, - { vsd_name: "Russia", vsd_countryid: "64bb1d2f-e56a-ea11-b812-005056830319" }, - ], - - other_country: { vsd_name: "Other", vsd_countryid: "" }, - other_province: { vsd_name: "Other", vsd_countryid: "", _vsd_countryid_value: "", vsd_code: "", vsd_provinceid: "" }, - other_city: { vsd_name: "Other", _vsd_countryid_value: "", _vsd_stateid_value: "", vsd_cityid: "" }, - - accepted_file_extensions: { - "pdf": true, - "png": true, - "jpeg": true, - "jpg": true, - "doc": true, - "docx": true, - "ppt": true, - } - - - - - -} \ No newline at end of file + canada_crm_id: '52e224c4-989a-e811-8155-480fcff4f6a1', + bc_crm_id: 'fde4dbca-989a-e811-8155-480fcff4f6a1', + preferred_police_detachments: [ + { vsd_name: 'Surrey RCMP Detachment', vsd_policedetachmentid: '7e9e3177-b5a4-e811-8164-480fcff407a1' }, + { vsd_name: 'Vancouver Police Department', vsd_policedetachmentid: '369f3177-b5a4-e811-8164-480fcff407a1' }, + { vsd_name: 'Abbotsford Police Department', vsd_policedetachmentid: '1c9e3177-b5a4-e811-8164-480fcff407a1' }, + { vsd_name: 'Kelowna RCMP Detachment', vsd_policedetachmentid: 'b89d3177-b5a4-e811-8164-480fcff407a1' }, + { vsd_name: 'Chilliwack RCMP Detachment', vsd_policedetachmentid: '429f3177-b5a4-e811-8164-480fcff407a1' }, + { vsd_name: 'New Westminster Police Department', vsd_policedetachmentid: '269e3177-b5a4-e811-8164-480fcff407a1' }, + { vsd_name: 'Burnaby RCMP Detachment', vsd_policedetachmentid: 'b8cf9469-ada4-e811-815f-480fcff4f621' }, + { vsd_name: 'Victoria Police Department', vsd_policedetachmentid: '169e3177-b5a4-e811-8164-480fcff407a1' }, + { vsd_name: 'Coquitlam RCMP Detachment', vsd_policedetachmentid: '709e3177-b5a4-e811-8164-480fcff407a1' }, + { vsd_name: 'Langley RCMP Detachment', vsd_policedetachmentid: '749e3177-b5a4-e811-8164-480fcff407a1' }, + { vsd_name: 'Nanaimo RCMP Detachment', vsd_policedetachmentid: '949e3177-b5a4-e811-8164-480fcff407a1' }, + { vsd_name: 'Kamloops RCMP Detachment', vsd_policedetachmentid: 'e09d3177-b5a4-e811-8164-480fcff407a1' } + ], + + preferred_countries: [ + { vsd_name: 'Other', vsd_countryid: '' }, + { vsd_name: 'Canada', vsd_countryid: '52e224c4-989a-e811-8155-480fcff4f6a1' }, + { vsd_name: 'United States of America', vsd_countryid: '49b05a13-e149-ea11-b816-00505683fbf4' }, + { vsd_name: 'Mexico', vsd_countryid: '39b05a13-e149-ea11-b816-00505683fbf4' }, + { vsd_name: 'United Kingdom', vsd_countryid: '55b05a13-e149-ea11-b816-00505683fbf4' }, + { vsd_name: 'Australia', vsd_countryid: '11b05a13-e149-ea11-b816-00505683fbf4' }, + { vsd_name: 'India', vsd_countryid: '2db05a13-e149-ea11-b816-00505683fbf4' }, + { vsd_name: 'Italy', vsd_countryid: '31b05a13-e149-ea11-b816-00505683fbf4' }, + { vsd_name: 'China', vsd_countryid: '15b05a13-e149-ea11-b816-00505683fbf4' }, + { vsd_name: 'Russia', vsd_countryid: '64bb1d2f-e56a-ea11-b812-005056830319' } + ], + + other_country: { vsd_name: 'Other', vsd_countryid: '' }, + other_province: { vsd_name: 'Other', vsd_countryid: '', _vsd_countryid_value: '', vsd_code: '', vsd_provinceid: '' }, + other_city: { vsd_name: 'Other', _vsd_countryid_value: '', _vsd_stateid_value: '', vsd_cityid: '' }, + + accepted_file_extensions: { + pdf: true, + png: true, + jpeg: true, + jpg: true, + doc: true, + docx: true, + ppt: true + } +}; diff --git a/vsd-app/ClientApp/src/main.ts b/vsd-app/ClientApp/src/main.ts index 446c583c..f7869a46 100644 --- a/vsd-app/ClientApp/src/main.ts +++ b/vsd-app/ClientApp/src/main.ts @@ -6,7 +6,7 @@ import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); if (window) { - window.console.log = function () { }; + window.console.log = function () {}; } } diff --git a/vsd-app/ClientApp/src/polyfills.ts b/vsd-app/ClientApp/src/polyfills.ts index 7194d4b3..946d3dec 100644 --- a/vsd-app/ClientApp/src/polyfills.ts +++ b/vsd-app/ClientApp/src/polyfills.ts @@ -46,14 +46,10 @@ import 'core-js/es6/reflect'; /** ALL Firefox browsers require the following to support `@angular/animation`. **/ // import 'web-animations-js'; // Run `npm install --save web-animations-js`. - - /*************************************************************************************************** * Zone JS is required by Angular itself. */ -import 'zone.js/dist/zone'; // Included with Angular CLI. - - +import 'zone.js/dist/zone'; // Included with Angular CLI. /*************************************************************************************************** * APPLICATION IMPORTS diff --git a/vsd-app/ClientApp/src/styles-font.scss b/vsd-app/ClientApp/src/styles-font.scss index 1b7b22af..af42c088 100644 --- a/vsd-app/ClientApp/src/styles-font.scss +++ b/vsd-app/ClientApp/src/styles-font.scss @@ -2,8 +2,8 @@ /* Controls Survey styles */ -@import "~@angular/material/theming"; -@import "~mygovbc-bootstrap-theme/dist/mygovbc-bootstrap-theme.min.css"; +@import '~@angular/material/theming'; +@import '~mygovbc-bootstrap-theme/dist/mygovbc-bootstrap-theme.min.css'; @include mat-core(); $primary: mat-palette($mat-grey, 400); $accent: mat-palette($mat-indigo, 500, A200, A400); @@ -11,374 +11,374 @@ $warn: mat-palette($mat-red, 500); $theme: mat-light-theme($primary, $accent, $warn); @include angular-material-theme($theme); body { - color: #494949; - background: #f2f2f2; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; - color: #494949; - font: MyriadWebPro, Calibri, Arial, "sans serif"; - /*width: 99%;*/ + color: #494949; + background: #f2f2f2; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + color: #494949; + font: MyriadWebPro, Calibri, Arial, 'sans serif'; + /*width: 99%;*/ } html { - background: #f2f2f2; + background: #f2f2f2; } .btn.btn-primary { - background-color: #38598a; - border: #38598a 1px solid; - color: #ffffff; - min-width: 120px; - font-size: 16px; - border-radius: 5px; + background-color: #38598a; + border: #38598a 1px solid; + color: #ffffff; + min-width: 120px; + font-size: 16px; + border-radius: 5px; } .btn.btn-secondary { - background-color: #fff; - border: #ccc 1px solid; - color: #003366; - min-width: 120px; - font-size: 16px; - border-radius: 3px; - display: inline-block; - padding: 6px 12px; - font-weight: 400; - line-height: 1.42857143; + background-color: #fff; + border: #ccc 1px solid; + color: #003366; + min-width: 120px; + font-size: 16px; + border-radius: 3px; + display: inline-block; + padding: 6px 12px; + font-weight: 400; + line-height: 1.42857143; } .btn-primary:hover { - background-color: rgba(0, 51, 102, 1) !important; - color: #ffffff; - border-color: #204d74; - border-radius: 5px; + background-color: rgba(0, 51, 102, 1) !important; + color: #ffffff; + border-color: #204d74; + border-radius: 5px; } .btn-secondary:hover { - background-color: #f2f2f2; + background-color: #f2f2f2; } .btn-secondary:focus { - border-color: #ccc; - box-shadow: 0 0 0 0.2rem #ccc; + border-color: #ccc; + box-shadow: 0 0 0 0.2rem #ccc; } .btn.btn-primary.sv_prev_btn { - background-color: #ccc; - border: #ccc 1px solid; - color: #000; - min-width: 120px; - font-size: 16px; - border-radius: 5px; + background-color: #ccc; + border: #ccc 1px solid; + color: #000; + min-width: 120px; + font-size: 16px; + border-radius: 5px; } .btn.btn-primary.sv_prev_btn:hover { - background-color: #2f567b !important; - color: #ffffff; - border-color: #204d74; - border-radius: 5px; + background-color: #2f567b !important; + color: #ffffff; + border-color: #204d74; + border-radius: 5px; } .btn.btn-warning { - color: #212529; - background-color: #f9ca54; - border-color: #f9ca54; - min-width: 120px; - font-size: 16px; - border-radius: 5px; + color: #212529; + background-color: #f9ca54; + border-color: #f9ca54; + min-width: 120px; + font-size: 16px; + border-radius: 5px; } .btn-warning:hover { - color: #212529; - background-color: #f8bf2f; - border-color: #f7bb23; + color: #212529; + background-color: #f8bf2f; + border-color: #f7bb23; } .btn-warning.focus, .btn-warning:focus { - box-shadow: 0 0 0 0.2rem rgba(217, 177, 78, 0.5); + box-shadow: 0 0 0 0.2rem rgba(217, 177, 78, 0.5); } .ctx-home { - background: #f2f2f2; + background: #f2f2f2; } .panel-footer { - background-color: #fff; - border-top: none; + background-color: #fff; + border-top: none; } p { - font-weight: Regular; - font-size: 14px #494949; + font-weight: Regular; + font-size: 14px #494949; } h1 { - font-weight: Semi-bold; - font-size: 36px; - color: #494949; + font-weight: Semi-bold; + font-size: 36px; + color: #494949; } h2 { - font-weight: Semi-bold; - font-size: 24px; - color: #494949; + font-weight: Semi-bold; + font-size: 24px; + color: #494949; } h3 { - font-weight: Semi-bold; - font-size: 20px; - color: #494949; + font-weight: Semi-bold; + font-size: 20px; + color: #494949; } h4 { - font-weight: Semi-bold; - font-size: 16px; - color: #494949; + font-weight: Semi-bold; + font-size: 16px; + color: #494949; } h5 { - font-size: 21px; - color: #494949; + font-size: 21px; + color: #494949; } select.form-control:not([size]):not([multiple]) { - height: auto; + height: auto; } .form-control { - // border-radius: 5px; - display: inline-block; + // border-radius: 5px; + display: inline-block; } .extra-padding-left { - padding-left: 15px; - padding-right: 15px; + padding-left: 15px; + padding-right: 15px; } @media (max-width: 575.98px) { - .extra-padding-left { - margin-left: 0; - } + .extra-padding-left { + margin-left: 0; + } } .alert { - padding: 3px 5px 3px; - margin-top: -9px; + padding: 3px 5px 3px; + margin-top: -9px; } .round-icon-wrapper { - height: 48px; - line-height: 55px; - width: 48px; - border-radius: 48px; - background-color: #7596c8; - text-align: center; - display: inline-block; + height: 48px; + line-height: 55px; + width: 48px; + border-radius: 48px; + background-color: #7596c8; + text-align: center; + display: inline-block; } .summary-table table { - border-spacing: 5px; - border-collapse: separate; - width: 100%; + border-spacing: 5px; + border-collapse: separate; + width: 100%; } .summary-table th { - background-color: #38598a; - color: #fff; - padding: 5px 5px 3px 10px; + background-color: #38598a; + color: #fff; + padding: 5px 5px 3px 10px; } .summary-table td { - padding: 5px; - background-color: #e1e8f2; + padding: 5px; + background-color: #e1e8f2; } .summary-table .row-alt { - background-color: #f1f4fa !important; + background-color: #f1f4fa !important; } .blue-header { - background-color: #38598a; - color: #fff; - padding: 10px 7px 7px 15px; - font-size: 16px; - font-weight: semi-bold; + background-color: #38598a; + color: #fff; + padding: 10px 7px 7px 15px; + font-size: 16px; + font-weight: semi-bold; } hr { - display: block; - height: 1px; - border: 0; - border-top: 1px solid #ccc; - margin: 1em 0; - padding: 0; + display: block; + height: 1px; + border: 0; + border-top: 1px solid #ccc; + margin: 1em 0; + padding: 0; } .error-states { - color: #d8292f; + color: #d8292f; } .error-summary { - background-color: #f2f2f2; - border: solid 1px transparent; - border-radius: 5px; - padding: 10px; - margin-bottom: 10px; - color: #d8292f; + background-color: #f2f2f2; + border: solid 1px transparent; + border-radius: 5px; + padding: 10px; + margin-bottom: 10px; + color: #d8292f; } .form-wrapper { - padding-left: 50px; - padding-right: 30px; + padding-left: 50px; + padding-right: 30px; } @media (max-width: 575.98px) { - .form-wrapper { - padding-left: 10px; - padding-right: 10px; - } + .form-wrapper { + padding-left: 10px; + padding-right: 10px; + } } .red-snackbar { - background: #f44336; + background: #f44336; } .green-snackbar { - background: #00ff21; + background: #00ff21; } .step { - border-bottom: 2px solid #fcba19; - display: inline-block; + border-bottom: 2px solid #fcba19; + display: inline-block; } .padded-section { - padding-left: 15px; + padding-left: 15px; } .notes { - background-color: #f2f2f2; - border: solid 1px transparent; - border-radius: 5px; - padding: 10px; - margin-bottom: 10px; + background-color: #f2f2f2; + border: solid 1px transparent; + border-radius: 5px; + padding: 10px; + margin-bottom: 10px; } .submitted-header { - background-color: rgba(56, 89, 138, 1); - border: 1px solid transparent; - border-bottom: none; - border-top-left-radius: 5px; - border-top-right-radius: 5px; - padding-left: 20px; - padding-right: 20px; - padding-bottom: 10px; - color: #fff !important; + background-color: rgba(56, 89, 138, 1); + border: 1px solid transparent; + border-bottom: none; + border-top-left-radius: 5px; + border-top-right-radius: 5px; + padding-left: 20px; + padding-right: 20px; + padding-bottom: 10px; + color: #fff !important; } .submitted-header h2 { - color: #fff !important; + color: #fff !important; } .submitted-content { - background-color: #eee; - padding: 20px; - margin-bottom: 20px; + background-color: #eee; + padding: 20px; + margin-bottom: 20px; } .submit-container { - background-color: #38598a; - border-bottom: solid 4px #ffcc00; + background-color: #38598a; + border-bottom: solid 4px #ffcc00; + color: #fff; + margin-bottom: 20px; + padding: 30px; + padding-top: 20px; + h2, + h3 { color: #fff; - margin-bottom: 20px; - padding: 30px; - padding-top: 20px; - h2, - h3 { - color: #fff; - } + } } .cancel-link { - cursor: pointer; + cursor: pointer; } .cancel-link:hover { - text-decoration: underline !important; + text-decoration: underline !important; } .inline-checkbox-label { - display: flex; + display: flex; } input.form-control { - &.date-picker { - background-color: #fff; - } + &.date-picker { + background-color: #fff; + } } .sticky-top { - z-index: 1000 !important; - background-color: white; + z-index: 1000 !important; + background-color: white; } .phone-number { - white-space: nowrap; - font-weight: 600; + white-space: nowrap; + font-weight: 600; } .learn-benefits { - margin-top: 25px; + margin-top: 25px; } .button-container { - position: relative; - margin: 30px 0 15px; + position: relative; + margin: 30px 0 15px; - // .btn { - // margin-left: 0 !important; - // } + // .btn { + // margin-left: 0 !important; + // } } .continue-btn { - float: right; + float: right; } .submit-grid { - display: inline-grid; - button { - margin-bottom: 5px; - } - .btn-submit { - width: 100%; - } - app-tool-tip { - position: absolute; - right: -20px; - top: 10px; - } - div { - position: relative; - } + display: inline-grid; + button { + margin-bottom: 5px; + } + .btn-submit { + width: 100%; + } + app-tool-tip { + position: absolute; + right: -20px; + top: 10px; + } + div { + position: relative; + } } .download-grid { - display: inline-grid; - button { - margin-bottom: 5px; - } + display: inline-grid; + button { + margin-bottom: 5px; + } } .white-icon { - color: white !important; + color: white !important; } .white-link { - color: white; + color: white; } .white-link:hover { - color: #79bff7; + color: #79bff7; } // .tooltip-icon .fa { @@ -386,87 +386,87 @@ input.form-control { // } .warning-message { - margin-top: 5vh; + margin-top: 5vh; } .hidden { - display: none !important; + display: none !important; } .right-buttons { - float: right; + float: right; } .left-buttons { - float: left; + float: left; } .print-button { - margin-right: 10px; + margin-right: 10px; } @media print { - .pagebreak { - page-break-before: always; - } - .hide-for-print { - display: none !important; - } - div { - display: table; - page-break-inside: avoid; - } + .pagebreak { + page-break-before: always; + } + .hide-for-print { + display: none !important; + } + div { + display: table; + page-break-inside: avoid; + } } .is-disabled { - opacity: 0.5; - text-decoration: none; - pointer-events: none; + opacity: 0.5; + text-decoration: none; + pointer-events: none; } .disabled-wrapper { - cursor: not-allowed; + cursor: not-allowed; } .disabled-stepper { - pointer-events: none; + pointer-events: none; } .loading-indicator { - position: fixed; - z-index: 999; - height: 6em; - width: 6em; - margin: auto; - top: 0; - left: 0; - bottom: 0; - right: 0; + position: fixed; + z-index: 999; + height: 6em; + width: 6em; + margin: auto; + top: 0; + left: 0; + bottom: 0; + right: 0; } .dark-overlay { - opacity: 0.7; - position: fixed; - top: 0; - left: 0; - width: 100%; + opacity: 0.7; + position: fixed; + top: 0; + left: 0; + width: 100%; } .no-app-field-botton-margin section { - margin-bottom: 0px !important; + margin-bottom: 0px !important; } .app-field-bold label { - font-weight: bold !important; + font-weight: bold !important; } .app-field-bold label > span { - font-weight: 400 !important; + font-weight: 400 !important; } .tooltip-info-container { - margin-top: 25px; - .tooltip-icon { - font-size: 20px; - } + margin-top: 25px; + .tooltip-icon { + font-size: 20px; + } } diff --git a/vsd-app/ClientApp/src/styles.scss b/vsd-app/ClientApp/src/styles.scss index 49b74f69..2aad3010 100644 --- a/vsd-app/ClientApp/src/styles.scss +++ b/vsd-app/ClientApp/src/styles.scss @@ -1,7 +1,7 @@ /* You can add global styles to this file, and also import other style files */ @import '~@angular/material/theming'; -@import "~mygovbc-bootstrap-theme/dist/mygovbc-bootstrap-theme.min.css"; +@import '~mygovbc-bootstrap-theme/dist/mygovbc-bootstrap-theme.min.css'; @include mat-core(); @@ -12,15 +12,10 @@ $warn: mat-palette($mat-red, 500); $theme: mat-light-theme($primary, $accent, $warn); @include angular-material-theme($theme); - - - - .ctx-home { background: #f2f2f2; } - h1 { font-size: 36px; padding-top: 15px; @@ -60,13 +55,13 @@ h3 { letter-spacing: 0.05em; } - .btn-group > .btn { // mygovbc CSS adds extra margin to buttons margin-right: 0; } -.btn-group-lg>.btn, .btn-lg { +.btn-group-lg > .btn, +.btn-lg { font-size: 20px; } @@ -77,45 +72,45 @@ h3 { // loading indicator @keyframes spin { - from { - transform: rotate(0); - } - to { - transform: rotate(360deg); - } + from { + transform: rotate(0); + } + to { + transform: rotate(360deg); + } } $indicator-color: #666; $indicator-size: 1em; $indicator-thickness: 0.2em; .loading-indicator { - &, &:after { - border-radius: 50%; - width: $indicator-size; - height: $indicator-size; - } - animation: spin 1.1s infinite linear; - border: $indicator-thickness solid transparent; - border-top-color: $indicator-color; - line-height: 1; - margin: 0 auto; - position: relative; - text-indent: -9999em; - transform: translateZ(0); - &:after { - position: absolute; - top: (- $indicator-thickness); - left: (- $indicator-thickness); - border: $indicator-thickness solid transparentize($indicator-color, 0.8); - content: ' '; - } + &, + &:after { + border-radius: 50%; + width: $indicator-size; + height: $indicator-size; + } + animation: spin 1.1s infinite linear; + border: $indicator-thickness solid transparent; + border-top-color: $indicator-color; + line-height: 1; + margin: 0 auto; + position: relative; + text-indent: -9999em; + transform: translateZ(0); + &:after { + position: absolute; + top: (-$indicator-thickness); + left: (-$indicator-thickness); + border: $indicator-thickness solid transparentize($indicator-color, 0.8); + content: ' '; + } } .page-load { font-size: 2rem; } - // survey styles .survey-container { @@ -140,8 +135,8 @@ $indicator-thickness: 0.2em; border-bottom: 2px solid #e0e3ee; } // .sv_row { - // border: 1px solid #ccf; - // padding: 10px; + // border: 1px solid #ccf; + // padding: 10px; // } .sv_page .sv_qstn { padding-top: 0; @@ -151,7 +146,6 @@ $indicator-thickness: 0.2em; margin: 1em 0; } .sv_page > .sv_row > .sv_qstn { - padding-top: 1em; } .sv_q_title { @@ -190,7 +184,8 @@ $indicator-thickness: 0.2em; margin: 0.5em 0; } -.survey-helptext, .survey-infotext { +.survey-helptext, +.survey-infotext { background: #f8faff; border: 1px solid #d3d3d8; border-radius: 4px; diff --git a/vsd-app/ClientApp/src/test.ts b/vsd-app/ClientApp/src/test.ts index 9bf72267..f5061990 100644 --- a/vsd-app/ClientApp/src/test.ts +++ b/vsd-app/ClientApp/src/test.ts @@ -7,10 +7,7 @@ import 'zone.js/dist/jasmine-patch'; import 'zone.js/dist/async-test'; import 'zone.js/dist/fake-async-test'; import { getTestBed } from '@angular/core/testing'; -import { - BrowserDynamicTestingModule, - platformBrowserDynamicTesting -} from '@angular/platform-browser-dynamic/testing'; +import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; // Unfortunately there's no typing for the `__karma__` variable. Just declare it as any. declare var __karma__: any; @@ -20,10 +17,7 @@ declare var require: any; __karma__.loaded = function () {}; // First, initialize the Angular testing environment. -getTestBed().initTestEnvironment( - BrowserDynamicTestingModule, - platformBrowserDynamicTesting() -); +getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); // Then we find all the tests. const context = require.context('./', true, /\.spec\.ts$/); // And load the modules. diff --git a/vsd-app/ClientApp/src/tsconfig.app.json b/vsd-app/ClientApp/src/tsconfig.app.json index 533b909d..258f5102 100644 --- a/vsd-app/ClientApp/src/tsconfig.app.json +++ b/vsd-app/ClientApp/src/tsconfig.app.json @@ -5,12 +5,7 @@ "module": "es2015", "baseUrl": "", "target": "es5", - "types": [ - "knockout" - ] + "types": ["knockout"] }, - "exclude": [ - "test.ts", - "**/*.spec.ts" - ] + "exclude": ["test.ts", "**/*.spec.ts"] } diff --git a/vsd-app/ClientApp/src/tsconfig.spec.json b/vsd-app/ClientApp/src/tsconfig.spec.json index a5bed5fa..ab81455d 100644 --- a/vsd-app/ClientApp/src/tsconfig.spec.json +++ b/vsd-app/ClientApp/src/tsconfig.spec.json @@ -5,18 +5,8 @@ "module": "commonjs", "target": "es5", "baseUrl": "", - "types": [ - "jasmine", - "node", - "knockout" - ] + "types": ["jasmine", "node", "knockout"] }, - "files": [ - "test.ts", - "polyfills.ts" - ], - "include": [ - "**/*.spec.ts", - "**/*.d.ts" - ] + "files": ["test.ts", "polyfills.ts"], + "include": ["**/*.spec.ts", "**/*.d.ts"] }