funky-framadate-front/src/app/services/config.service.ts

378 lines
10 KiB
TypeScript
Raw Normal View History

2019-12-03 17:20:57 +01:00
import {Injectable} from '@angular/core';
import {PollConfig} from '../config/PollConfig';
2020-01-15 15:55:15 +01:00
import {HttpClient, HttpHeaders} from "@angular/common/http";
2019-12-03 17:20:57 +01:00
import {environment} from "../../environments/environment";
import {MessageService} from 'primeng/api';
2019-12-03 17:20:57 +01:00
/**
* le service transverse à chaque page qui permet de syncroniser la configuration de sondage souhaitée
*/
@Injectable({
providedIn: 'root'
})
export class ConfigService extends PollConfig {
2020-01-16 11:46:31 +01:00
2020-01-15 11:40:39 +01:00
loading: boolean = false;
2019-12-03 17:20:57 +01:00
baseHref: any = environment.baseApiHref;
myPolls: any;// list of retrieved polls from the backend api
2020-01-15 15:55:15 +01:00
constructor(private http: HttpClient,
private messageService: MessageService) {
2019-12-03 17:20:57 +01:00
super();
}
set(key, val) {
this[key] = val;
}
2020-01-15 15:55:15 +01:00
clear() {
this.messageService.clear();
}
/**
* generate unique id to have a default url for future poll
*/
makeUuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
makeSlug(str?: string) {
if (!str) {
str = this.creationDate.getFullYear() + '_' + (this.creationDate.getMonth() + 1) + '_' + this.creationDate.getDate() + '_' + this.myName + '_' + this.title;
}
str = str.replace(/^\s+|\s+$/g, ''); // trim
str = str.toLowerCase();
// remove accents, swap ñ for n, etc
var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
var to = "aaaaeeeeiiiioooouuuunc------";
for (var i = 0, l = from.length; i < l; i++) {
str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
}
str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
.replace(/\s+/g, '-') // collapse whitespace and replace by -
.replace(/-+/g, '-'); // collapse dashes
return str;
}
/**
* add some days to a date, to compute intervals
* @param days
* @param date
*/
addDaysToDate(days: number, date: Date) {
date = new Date(date.valueOf());
date.setDate(date.getDate() + days);
return date;
};
2019-12-04 12:45:50 +01:00
/** ==================================
*
* poll public calls to get non authenticated info
*
* ==================================/
/**
* convert current poll config to a payload to send to the backend API
*/
2019-12-03 17:20:57 +01:00
getPollConfig() {
const jsonConfig = {
method: 'POST',
data: {
owner: {
email: this.myEmail,
pseudo: this.myName,
},
title: this.title,
description: this.description,
type: this.pollType,
visibility: this.visibility,
voteChoices: this.voteChoices,
allowSeveralHours: this.allowSeveralHours,
expirationDate: this.expirationDate,
passwordAccess: this.passwordAccess,
password: this.password,
customUrl: this.customUrl,
canModifyAnswers: this.canModifyAnswers,
whoModifiesAnswers: this.whoModifiesAnswers,
dateList: this.dateList,
timeList: this.timeList,
answers: this.answers,
}
};
console.log('jsonConfig', jsonConfig);
return jsonConfig
}
2020-01-15 15:55:15 +01:00
makeHeaders(bodyContent?: any) {
const headerDict = {
'Charset': 'UTF-8',
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
'Access-Control-Allow-Origin': '*'
};
const requestOptions = {
headers: new HttpHeaders(headerDict),
body: bodyContent
};
return requestOptions;
}
checkIfSlugIsUniqueInDatabase(slug: string) {
this.customUrlIsUnique = null;
this.loading = true;
this.http.get(`${this.baseHref}/check-slug-is-uniq`,
this.makeHeaders({slug: this.customUrl}),
)
.subscribe((res: any) => {
this.customUrlIsUnique = res.data.isUnique;
this.loading = false;
},
(e) => this.handleError(e))
;
}
2019-12-04 12:45:50 +01:00
/**
* search in localstorage, fallback asking the backend to send an email to the owner if it exists
* @param email
*/
findPollsByEmail(email: string) {
this.findLocalStorageData();
// If no key is found in the localstorage, ask the backend to send an email to the user
this.myEmail = email;
2020-01-15 11:40:39 +01:00
this.loading = true;
this.http.get(`${this.baseHref}/my-polls`,
2020-01-15 15:55:15 +01:00
this.makeHeaders({email: this.myEmail}),
2020-01-15 11:40:39 +01:00
)
2019-12-04 12:45:50 +01:00
.subscribe(res => {
// message: 'Trouvé! Allez voir votre boite email',
this.myPolls = res;
console.log('res', res);
this.loading = false;
2020-01-15 15:55:15 +01:00
this.messageService.add({
severity: 'success',
summary: 'Service Message',
detail: 'Via MessageService'
});
}, (e) => {
2020-01-15 17:55:22 +01:00
this.handleError(e)
2020-01-15 15:55:15 +01:00
}
2019-12-04 12:45:50 +01:00
)
}
/**
* display error message depending on the response of the backend
* @param err
*/
2019-12-03 17:20:57 +01:00
handleError(err: any) {
2019-12-04 12:45:50 +01:00
// TODO handle a toast message
2020-01-15 15:55:15 +01:00
console.error('err', err);
2020-01-15 11:40:39 +01:00
this.loading = false;
2020-01-15 15:55:15 +01:00
this.messageService.add({severity: 'warning', summary: "Erreur lors de l'appel "});
2019-12-03 17:20:57 +01:00
}
findLocalStorageData() {
// TODO check if the person has a key to retrieve her polls
}
/**
2020-01-15 15:55:15 +01:00
* get one poll by its slug name
2019-12-03 17:20:57 +01:00
* @param url
*/
getPollByURL(url: string) {
2020-01-15 15:55:15 +01:00
this.http.get(`${this.baseHref}/poll/${url}`, this.makeHeaders()).subscribe(
2019-12-03 17:20:57 +01:00
(res: any) => {
this.myPolls = res.data;
2020-01-15 15:55:15 +01:00
}, (e) => {
this.handleError(e)
}
2019-12-03 17:20:57 +01:00
);
}
/**
2019-12-04 12:45:50 +01:00
* GET
* api/v1/poll/{id}
2019-12-03 17:20:57 +01:00
* @param id
*/
2019-12-04 12:45:50 +01:00
getPollById(id: string, password: string) {
2020-01-15 11:40:39 +01:00
2019-12-04 12:45:50 +01:00
this.http
.get(`${this.baseHref}/poll/${id}`,
2020-01-15 15:55:15 +01:00
this.makeHeaders({body: password}))
2019-12-04 12:45:50 +01:00
.subscribe(
(res: any) => {
this.myPolls = res.data;
2020-01-15 15:55:15 +01:00
}, (e) => {
this.handleError(e)
}
2019-12-04 12:45:50 +01:00
);
}
/**
* GET
* api/v1/my-polls
* @param ownerEmail
*/
getMyPolls(ownerEmail: string) {
this.http
.get(`${this.baseHref}/my-polls`,
2020-01-15 15:55:15 +01:00
this.makeHeaders({ownerEmail: ownerEmail})
)
2019-12-04 12:45:50 +01:00
.subscribe(
(res: any) => {
this.myPolls = res.data;
2020-01-15 15:55:15 +01:00
}, (e) => {
this.handleError(e)
}
2019-12-04 12:45:50 +01:00
);
}
/**
* action of the form
*/
createPoll() {
console.log('sends the form');
// alert('envoi de formulaire pour création de sondage en XHR à faire');
2020-01-15 15:55:15 +01:00
this.http.get(`${this.baseHref}/`, this.makeHeaders())
2019-12-04 12:45:50 +01:00
.subscribe((res) => {
console.log('res', res);
this.createPollFromConfig(this.getPollConfig())
},
this.handleError
)
;
}
/**
* POST
* /api/v1/poll/{id}/poll
* @param config
*/
createPollFromConfig(config: any) {
2020-01-15 15:55:15 +01:00
this.http.post(`${this.baseHref}/poll`, this.makeHeaders({config: config}))
2019-12-04 12:45:50 +01:00
.subscribe((res: any) => {
// redirect to the page to administrate the new poll
2020-01-15 15:55:15 +01:00
this.messageService.add({severity: 'success', summary: 'Sondage Créé',});
2019-12-04 12:45:50 +01:00
this.selectedPoll = res;
this.pollId = res.pollId;
2020-01-15 15:55:15 +01:00
}, (e) => {
this.handleError(e)
}
2019-12-04 12:45:50 +01:00
);
}
/**
* UPDATE
* /api/v1/poll/{id}/vote
* @param voteStack
*/
updatePoll(voteStack: any) {
2020-01-15 15:55:15 +01:00
this.http.put(
`${this.baseHref}/poll/${this.pollId}`,
voteStack,
this.makeHeaders()
)
2019-12-04 12:45:50 +01:00
.subscribe((res: any) => {
2020-01-15 15:55:15 +01:00
this.messageService.add({
severity: 'success',
summary: 'Sondage mis à jour',
});
2019-12-04 12:45:50 +01:00
this.myPolls = res;
2020-01-15 15:55:15 +01:00
}, (e) => {
this.handleError(e)
}
2019-12-04 12:45:50 +01:00
);
}
/**
* POST
* /api/v1/poll/{id}/vote
* @param voteStack
*/
addVote(voteStack: any) {
2020-01-15 15:55:15 +01:00
this.http.post(
`${this.baseHref}/poll/${this.pollId}/vote`,
voteStack,
this.makeHeaders())
2019-12-04 12:45:50 +01:00
.subscribe((res: any) => {
2020-01-15 15:55:15 +01:00
this.messageService.add({severity: 'success', summary: 'Vote ajouté'});
2019-12-04 12:45:50 +01:00
alert("succès!");
this.myPolls = res;
2020-01-15 15:55:15 +01:00
}, (e) => {
this.handleError(e)
}
2019-12-04 12:45:50 +01:00
);
2019-12-03 17:20:57 +01:00
}
2019-12-04 12:45:50 +01:00
/**
* UPDATE
* /api/v1/poll/{id}/vote
* @param voteStack
*/
updateVote(voteStack: any) {
2020-01-15 15:55:15 +01:00
this.http.put(
`${this.baseHref}/poll/${this.pollId}/vote`,
voteStack,
this.makeHeaders())
2019-12-04 12:45:50 +01:00
.subscribe((res: any) => {
2020-01-15 15:55:15 +01:00
this.messageService.add({severity: 'success', summary: 'Vote mis à jour'});
2019-12-04 12:45:50 +01:00
this.myPolls = res;
2020-01-15 15:55:15 +01:00
}, (e) => {
this.handleError(e)
}
2019-12-04 12:45:50 +01:00
);
}
/**
* POST
* /api/v1/poll/{id}/comment
* @param comment
*/
addComment(comment: any) {
2020-01-15 15:55:15 +01:00
this.http.post(
`${this.baseHref}/poll/${this.pollId}/comment`,
comment,
this.makeHeaders())
2019-12-04 12:45:50 +01:00
.subscribe((res: any) => {
2020-01-15 15:55:15 +01:00
this.messageService.add({
severity: 'success',
summary: 'Commentaire Créé',
detail: 'Via MessageService'
});
}, (e) => {
this.handleError(e)
}
2019-12-04 12:45:50 +01:00
);
}
/**
* administrator calls
*/
2019-12-03 17:20:57 +01:00
}