funky-framadate-front/src/app/core/models/poll.model.ts

90 lines
2.7 KiB
TypeScript

import { environment } from 'src/environments/environment';
import { v4 as uuidv4 } from 'uuid';
import { ResponseType } from '../enums/response-type.enum';
import { PollUserAnswers } from './poll-user-answers.model';
import { Choice } from './choice.model';
import { Comment } from './comment.model';
import { Configuration } from './configuration.model';
import { User } from './user.model';
export class Poll {
constructor(
public owner: User,
public question: string,
public description?: string,
public slug: string = uuidv4(),
public configuration: Configuration = new Configuration(),
public comments: Comment[] = [],
public choices: Choice[] = [],
public answersByChoiceByParticipant: Map<string, Map<string, ResponseType>> = new Map<
string,
Map<string, ResponseType>
>(),
public answers: PollUserAnswers[] = []
) {}
public getAdministrationUrl(): string {
return `${environment.api.baseHref}/administration/polls/${this.slug}`;
}
public getParticipationUrl(): string {
return `${environment.api.baseHref}/participation/polls/${this.slug}`;
}
public static adaptFromLocalJsonServer(
item: Pick<
Poll,
| 'owner'
| 'question'
| 'description'
| 'slug'
| 'configuration'
| 'comments'
| 'choices'
| 'answersByChoiceByParticipant'
| 'answers'
>
): Poll {
const poll = new Poll(
new User(item.owner.pseudo, item.owner.email, undefined),
item.question,
item.description,
item.slug,
item.configuration,
item.comments
.map(
(c: Pick<Comment, 'author' | 'content' | 'dateCreated'>) =>
new Comment(c.author, c.content, new Date(c.dateCreated))
)
.sort(Comment.sortChronologically),
item.choices.map((c: Pick<Choice, 'label' | 'imageUrl' | 'participants' | 'imageUrl'>) => {
const choice = new Choice(c.label, c.imageUrl, new Map(c.participants));
choice.participants.forEach((value, key) => {
choice.participants.set(key, new Set(value));
});
choice.updateCounts();
return choice;
})
);
// handle answersByChoiceByParticipant
for (const [pseudo, answersByChoice] of Object.entries(item.answersByChoiceByParticipant)) {
if (!poll.answersByChoiceByParticipant.has(pseudo)) {
poll.answersByChoiceByParticipant.set(pseudo, new Map<string, ResponseType>());
}
for (const [choiceLabel, answer] of Object.entries(answersByChoice)) {
poll.answersByChoiceByParticipant.get(pseudo).set(choiceLabel, answer as ResponseType);
}
}
// handle answers
poll.answers = item.answers.map(
(pollUserAnswers: Pick<PollUserAnswers, 'pseudo' | 'token' | 'responsesByChoices'>) =>
new PollUserAnswers(pollUserAnswers.pseudo, pollUserAnswers.token, pollUserAnswers.responsesByChoices)
);
return poll;
}
}