diff --git a/src/app/components/candidate/candidate.component.html b/src/app/components/candidate/candidate.component.html index 91c5fa6..383c100 100644 --- a/src/app/components/candidate/candidate.component.html +++ b/src/app/components/candidate/candidate.component.html @@ -12,7 +12,7 @@ - - - - - - - - - - - - - - - diff --git a/src/app/components/candidate/candidate.component.ts b/src/app/components/candidate/candidate.component.ts index ac97591..8538ff2 100644 --- a/src/app/components/candidate/candidate.component.ts +++ b/src/app/components/candidate/candidate.component.ts @@ -18,7 +18,7 @@ export class CandidateComponent implements OnInit { } onVote(vote: number) { - this.voteService.setVote(this.candidate, vote); + this.voteService.setVote(this.candidate, this.auth.user, vote); } } diff --git a/src/app/services/vote.service.ts b/src/app/services/vote.service.ts index 2349b95..d7ef6cb 100644 --- a/src/app/services/vote.service.ts +++ b/src/app/services/vote.service.ts @@ -1,6 +1,5 @@ import { Injectable } from '@angular/core'; import { MatSnackBar } from '@angular/material'; -import { AuthService } from './auth.service'; import { AngularFirestore } from '@angular/fire/firestore'; import { Candidate } from '../types/candidate.model'; @@ -10,23 +9,35 @@ import { Candidate } from '../types/candidate.model'; export class VoteService { constructor(private db: AngularFirestore, - private snackBar: MatSnackBar, - private auth: AuthService) { } + private snackBar: MatSnackBar) { } - setVote(candidate: Candidate, vote: number) { - if (!this.auth.user) { + setVote(candidate: Candidate, user: User, vote: number) { + if (!user) { this.snackBar.open('Please login to vote'); return; } - candidate.votes = candidate.votes || {}; + return Promise.all([ + this.updateCandidateVotes(candidate, user, vote), + this.updateUserVotes(user, vote) + ]) + } - let currentVote = (candidate.votes[this.auth.user.uid] || 0) + vote; + updateCandidateVotes(candidate: Candidate, user: User, vote: number) { + candidate.votes = candidate.votes || {}; + let currentVote = (candidate.votes[user.uid] || 0) + vote; if (currentVote < 0) currentVote = 0; - candidate.votes[this.auth.user.uid] = currentVote; + candidate.votes[user.uid] = currentVote; + candidate.totalVotes = (candidate.totalVotes || 0) + vote; + + return this.db.doc(`candidates/${candidate.user.uid}`).update(candidate); + } - this.db.doc(`candidates/${candidate.user.uid}`).update(candidate) + updateUserVotes(user: User, vote: number) { + let userTotalVotes = (user.totalVotes || 0) + vote; + if (userTotalVotes < 0) userTotalVotes = 0; + return this.db.doc(`users/${user.uid}`).update({ totalVotes: userTotalVotes }); } } diff --git a/src/app/types/user.model.ts b/src/app/types/user.model.ts index 7ecfe7b..61ed754 100644 --- a/src/app/types/user.model.ts +++ b/src/app/types/user.model.ts @@ -4,4 +4,5 @@ interface User { photoURL?: string; displayName?: string; myCustomData?: string; + totalVotes?: number; }