Skip to content

Commit

Permalink
tidy up
Browse files Browse the repository at this point in the history
  • Loading branch information
cmak34 committed Apr 5, 2023
1 parent c63210d commit f1cdfd8
Show file tree
Hide file tree
Showing 8 changed files with 91 additions and 44 deletions.
4 changes: 3 additions & 1 deletion src/app/components/edit-survey/edit-survey.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ export class EditSurveyComponent {
})) || [], [Validators.required]),
isPublished: this.fb.control((this.survey) ? this.survey?.isPublished : true, []),
})
this.addQuestion()
if (!this.survey) {
this.addQuestion()
}
}

public async submit() {
Expand Down
4 changes: 2 additions & 2 deletions src/app/components/header/header.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
<button *ngIf="auth?.user" routerLink="/dashboard" class="m-r-10" nz-button nzType="text">
<span nz-icon nzType="dashboard" nzTheme="outline"></span> Dashboard
</button>
<button *ngIf="auth.user" routerLink="/manage-users" class="m-r-10" nz-button nzType="text" [disabled]="auth.userProfile?.role != 'admin'">
<button *ngIf="auth.user" routerLink="/manage-users" class="m-r-10" nz-button nzType="text" [disabled]="(auth.profile$ | async)?.role != 'admin'">
<span nz-icon nzType="user" nzTheme="outline"></span> Users
</button>
<button *ngIf="auth?.user" (click)="logout()" class="m-r-10" nz-button nzType="text">
Expand All @@ -36,7 +36,7 @@
<button *ngIf="auth?.user" routerLink="/dashboard" class="m-r-10" nz-button nzType="text" nz-tooltip nzTooltipTitle="Dashboard">
<span nz-icon nzType="dashboard" nzTheme="outline"></span>
</button>
<button *ngIf="auth.user" routerLink="/manage-users" class="m-r-10" nz-button nzType="text" [disabled]="auth.userProfile?.role != 'admin'" nz-tooltip nzTooltipTitle="User">
<button *ngIf="auth.user" routerLink="/manage-users" class="m-r-10" nz-button nzType="text" [disabled]="(auth.profile$ | async)?.role != 'admin'" nz-tooltip nzTooltipTitle="User">
<span nz-icon nzType="user" nzTheme="outline"></span>
</button>
<button *ngIf="auth?.user" (click)="logout()" class="m-r-10" nz-button nzType="text" nz-tooltip nzTooltipTitle="Logout">
Expand Down
61 changes: 43 additions & 18 deletions src/app/components/view-survey/view-survey.component.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component, Input, OnInit } from '@angular/core';
import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { Survey } from 'src/app/model/Survey';
import { catchError, map, Observable, of, tap } from 'rxjs';
import { AngularFirestore } from '@angular/fire/compat/firestore';
Expand All @@ -13,44 +13,69 @@ import { AuthService } from 'src/app/service/auth.service';
templateUrl: './view-survey.component.html',
styleUrls: ['./view-survey.component.less']
})
export class ViewSurveyComponent implements OnInit {
export class ViewSurveyComponent implements OnInit, OnDestroy {
@Input() public survey?: Survey;
public results: Result[] = [];
public results$: Observable<Result[]> = of([])
public isExporting = false;
public subscription: any;

constructor(
private modalRef: NzModalRef,
private notification: NzNotificationService,
private afs: AngularFirestore,
private auth : AuthService
private auth: AuthService
) {

}

ngOnInit(): void {
const currentUserId = this.auth.user?.uid;
if (currentUserId && this.survey?.id) {
this.results$ = this.afs.collection<Result>("results", ref => ref.where("surveyId", "==", this.survey?.id).orderBy("createdTime", "desc"))
.snapshotChanges()
.pipe(
map(actions => actions.map(action => ({ ...action.payload.doc.data() as any, id: action.payload.doc.id }))),
tap(actions => this.results = actions || []),
catchError((error) => {
console.error("Error getting survey results:", error);
this.notification.error("Error", `Error getting survey results: ${error}`);
return of([]);
})
)
}
this.subscription = this.auth.profile$.subscribe(user => {
if (!this.survey?.id || !this.survey?.ownerId || !user?.id || (user?.role == "user" && this.survey?.ownerId != user?.id)) {
this.modalRef.close()
} else if (user.role == "admin") {
this.results$ = this.afs.collection<Result>("results", ref => ref
.where("surveyId", "==", this.survey?.id)
.orderBy("createdTime", "desc")
).snapshotChanges()
.pipe(
map(actions => actions.map(action => ({ ...action.payload.doc.data() as any, id: action.payload.doc.id }))),
tap(actions => this.results = actions || []),
catchError((error) => {
console.error("Error getting survey results:", error);
this.notification.error("Error", `Error getting survey results: ${error}`);
return of([]);
})
)
} else if (user.role == "user" && this.survey?.ownerId == user?.id) {
this.results$ = this.afs.collection<Result>("results", ref => ref
.where("surveyId", "==", this.survey?.id)
.where("ownerId", "==", user?.id)
.orderBy("createdTime", "desc")
).snapshotChanges()
.pipe(
map(actions => actions.map(action => ({ ...action.payload.doc.data() as any, id: action.payload.doc.id }))),
tap(actions => this.results = actions || []),
catchError((error) => {
console.error("Error getting survey results:", error);
this.notification.error("Error", `Error getting survey results: ${error}`);
return of([]);
})
)
}
})
}

ngOnDestroy(): void {
this.subscription.unsubscribe();
}

public close() {
this.modalRef.close();
}

public exportToCsv() {
try {
try {
if (this.results.length) {
this.isExporting = true
const header = this.survey?.questions.map(question => question.label).join(',') + '\n';
Expand Down
1 change: 1 addition & 0 deletions src/app/model/Result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import firebase from 'firebase/compat/app';
export interface Result {
id: string;
surveyId: string;
ownerId: string;
answers: any[];
createdTime: firebase.firestore.Timestamp;
}
41 changes: 29 additions & 12 deletions src/app/pages/dashboard/dashboard.component.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component, OnInit } from '@angular/core';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Survey } from 'src/app/model/Survey';
import { AngularFirestore } from '@angular/fire/compat/firestore';
import { catchError, map, Observable, of } from 'rxjs';
Expand All @@ -13,9 +13,10 @@ import { AuthService } from 'src/app/service/auth.service';
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.less']
})
export class DashboardComponent implements OnInit{
export class DashboardComponent implements OnInit, OnDestroy {
public isDeleting: boolean = false;
public surveys$: Observable<Survey[]> = of([]);
public subscription: any;

constructor(
private modal: NzModalService,
Expand All @@ -25,20 +26,36 @@ export class DashboardComponent implements OnInit{
) { }

ngOnInit(): void {
const currentUserId = this.auth.user?.uid;
if (currentUserId){
this.surveys$ = this.afs.collection<Survey>("surveys",ref=> ref
.where("ownerId","==",currentUserId)
.orderBy("createdTime","desc"))
.snapshotChanges()
.pipe(
this.subscription = this.auth.profile$.subscribe((user) => {
if (user?.role == "admin") {
this.surveys$ = this.afs.collection<Survey>("surveys", ref => ref
.orderBy("createdTime", "desc"))
.snapshotChanges()
.pipe(
map(actions => actions.map(action => ({ ...action.payload.doc.data() as any, id: action.payload.doc.id }))),
catchError((error) => {
console.error("Error getting surveys:", error);
this.notification.error("Error", `Error getting surveys: ${error}`);
return of([]);
}));
}
} else if (user?.role == "user") {
this.surveys$ = this.afs.collection<Survey>("surveys", ref => ref
.where("ownerId", "==", user?.id)
.orderBy("createdTime", "desc"))
.snapshotChanges()
.pipe(
map(actions => actions.map(action => ({ ...action.payload.doc.data() as any, id: action.payload.doc.id }))),
catchError((error) => {
console.error("Error getting surveys:", error);
this.notification.error("Error", `Error getting surveys: ${error}`);
return of([]);
}));
}
});
}

ngOnDestroy(): void {
this.subscription.unsubscribe();
}

public addSurvey() {
Expand Down Expand Up @@ -72,7 +89,7 @@ export class DashboardComponent implements OnInit{

public viewSurvey(survey: Survey) {
this.modal.create({
nzTitle: `View ${survey.title || "Untitled Survey"}`,
nzTitle: undefined,
nzContent: ViewSurveyComponent,
nzComponentParams: {
survey: survey
Expand All @@ -89,7 +106,7 @@ export class DashboardComponent implements OnInit{
this.isDeleting = false
} catch (error) {
this.isDeleting = false
console.log(error)
console.log(error)
this.notification.error("error", `Error: ${error}`)
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/app/pages/survey/survey.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ <h3 class="m-b-10">{{ survey.desc }}</h3>
</div>
</div>
<ng-template #display404>
<nz-result nzStatus="404" nzTitle="404" nzSubTitle="Sorry, the survey you visited does not exist anymore.">
<nz-result *ngIf="!isInit" nzStatus="404" nzTitle="404" nzSubTitle="Sorry, the survey you visited does not exist anymore.">
<div nz-result-extra>
<button type="button" nz-button nzType="primary" routerLink="/">Back Home</button>
</div>
Expand Down
3 changes: 3 additions & 0 deletions src/app/pages/survey/survey.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { Router } from '@angular/router';
styleUrls: ['./survey.component.less']
})
export class SurveyComponent implements OnInit {
public isInit = true;
public isLoading: boolean = false;
public survey?: Survey;
public form?: FormGroup;
Expand Down Expand Up @@ -83,6 +84,7 @@ export class SurveyComponent implements OnInit {
this.notification.error('Error', `Sorry, error has expired: ${error}`);
} finally {
this.isLoading = false;
this.isInit = false;
}
}
}
Expand All @@ -100,6 +102,7 @@ export class SurveyComponent implements OnInit {
answers: this.survey?.questions.map(
(_question, index) => this.form?.value[`${index}`] || null
),
ownerId: this.survey?.ownerId,
createdTime: serverTimestamp(),
});
this.isLoading = false;
Expand Down
19 changes: 9 additions & 10 deletions src/app/service/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@ import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import { AngularFirestore } from '@angular/fire/compat/firestore';
import firebase from 'firebase/compat/app';
import { filter, map } from 'rxjs';
import { Observable, filter, map, of } from 'rxjs';

import { User } from 'src/app/model/User';
@Injectable({
providedIn: 'root'
})
export class AuthService {
public user: firebase.User | null = null
public userProfile: User | null = null;
public profile$: Observable<User | null> = of(null);
public static EMAIL_PATTERN = /^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}(\.[a-zA-Z]{2,6})?)$/

constructor(
private afAuth: AngularFireAuth,
private afAuth: AngularFireAuth,
private afs: AngularFirestore
) {
this.getAuth();
Expand All @@ -24,7 +24,12 @@ export class AuthService {
this.afAuth.onAuthStateChanged(async (user) => {
this.user = user;
if (user && user?.uid) {
await this.getUserRole(user?.uid);
this.profile$ = this.afs.collection('users').doc(user?.uid).snapshotChanges().pipe(
filter((user) => user.payload.exists),
map((user) => ({ ...user.payload.data() as any, id: user.payload.id }) as User)
)
} else {
this.profile$ = of(null);
}
});
}
Expand All @@ -49,10 +54,4 @@ export class AuthService {
})
}
}
public async getUserRole(uid: string): Promise<void> {
this.userProfile = await this.afs.collection('users').doc(uid).get().pipe(
filter((user) => user.exists),
map((user) => ({...user.data() as any, id: user.id }) as User)
).toPromise() || null;
}
}

0 comments on commit f1cdfd8

Please sign in to comment.