send vote stack to a new endpoint

This commit is contained in:
Tykayn 2021-06-07 11:30:10 +02:00 committed by tykayn
parent 36fe52aa82
commit e4ed956970
11 changed files with 114 additions and 59 deletions

View File

@ -7,6 +7,6 @@ export class Owner {
public email: string = '_nonexistent_contact@cipherbliss.com', public email: string = '_nonexistent_contact@cipherbliss.com',
public polls: Poll[] = [], public polls: Poll[] = [],
public role?: UserRole, public role?: UserRole,
public token?: string public modifier_token?: string
) {} ) {}
} }

View File

@ -3,6 +3,7 @@ import { Owner } from './owner.model';
export class Stack { export class Stack {
public id: number; public id: number;
public poll_custom_url: string;
public pseudo = 'Choque Nourrice'; public pseudo = 'Choque Nourrice';
public comment = 'Le beau commentaire de Choque Nourrice'; public comment = 'Le beau commentaire de Choque Nourrice';
public owner: Owner = new Owner(); public owner: Owner = new Owner();

View File

@ -78,27 +78,6 @@ export class ApiService {
}; };
} }
private static handleError(error): void {
// this.loaderService.setStatus(true);
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
// this.loaderService.setStatus(false);
}
public async createPoll(poll: Poll): Promise<Subscription> { public async createPoll(poll: Poll): Promise<Subscription> {
// this.loaderService.setStatus(true); // this.loaderService.setStatus(true);
console.log('createPoll config', poll); console.log('createPoll config', poll);
@ -111,17 +90,16 @@ export class ApiService {
/** /**
* send a new vote stack * send a new vote stack
* @param poll
* @param vote_stack * @param vote_stack
*/ */
public sendNewVoteStackOfPoll(poll: Poll, vote_stack: Stack): Promise<void> { public sendNewVoteStackOfPoll(vote_stack: Stack): Promise<void> {
// api_new_vote_stack POST ANY ANY /api/v1/poll/{id}/answer // api_new_vote_stack POST ANY ANY /api/v1/poll/{id}/answer
console.log('vote_stack', vote_stack); console.log('vote_stack', vote_stack);
console.log('this.baseHref', this.baseHref); console.log('this.baseHref', this.baseHref);
const headers = ApiService.makeHeaders(vote_stack); const headers = ApiService.makeHeaders(vote_stack);
console.log('headers', headers); console.log('headers', headers);
const url = `${this.baseHref}/vote/poll/${poll.custom_url}/answer`; const url = `${this.baseHref}/vote-stack/`;
const axiosconf = { const axiosconf = {
url, url,
@ -174,8 +152,8 @@ export class ApiService {
public async getPollByCustomUrl(slug: string): Promise<Poll | undefined> { public async getPollByCustomUrl(slug: string): Promise<Poll | undefined> {
try { try {
console.log('fetch API : asking for poll with custom_url=' + slug);
const response: AxiosResponse<Poll> = await this.axiosInstance.get<Poll>(`${this.pollsEndpoint}/${slug}`); const response: AxiosResponse<Poll> = await this.axiosInstance.get<Poll>(`${this.pollsEndpoint}/${slug}`);
console.log('fetch API : asking for poll with custom_url=' + slug, { response });
return response && response.data && !Array.isArray(response.data) ? response.data : undefined; return response && response.data && !Array.isArray(response.data) ? response.data : undefined;
} catch (error) { } catch (error) {
@ -227,7 +205,10 @@ export class ApiService {
public async sendUpdateVoteStack(vote_stack: Stack) { public async sendUpdateVoteStack(vote_stack: Stack) {
try { try {
return await this.axiosInstance.patch(`${this.baseHref}/vote_stack/${vote_stack.id}`, vote_stack); return await this.axiosInstance.patch(
`${this.baseHref}/vote-stack/${vote_stack.id}/token/${vote_stack.owner.modifier_token}/`,
vote_stack
);
} catch (error) { } catch (error) {
ApiService.handleError(error); ApiService.handleError(error);
} }
@ -286,4 +267,24 @@ export class ApiService {
///////////////////// /////////////////////
// PRIVATE METHODS // // PRIVATE METHODS //
///////////////////// /////////////////////
private static handleError(error): void {
// this.loaderService.setStatus(true);
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.error('Error response data', error.response.data);
console.error('Error response status', error.response.status);
console.error('Error response headers', error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log('ErrorRequest', error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
// this.loaderService.setStatus(false);
}
} }

View File

@ -43,16 +43,10 @@ export class PollService implements Resolve<Poll> {
* @param state * @param state
*/ */
public async resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<Poll> { public async resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<Poll> {
console.log('resolve route,state', route, state);
const segments: string[] = state.url.split('/'); const segments: string[] = state.url.split('/');
const wantedcustom_url: string = segments.includes('poll') ? segments[segments.indexOf('poll') + 1] : ''; const wantedcustom_url: string = segments.includes('poll') ? segments[segments.indexOf('poll') + 1] : '';
// FIXME should be handled by routing
if (!wantedcustom_url && state.url.includes('administration')) {
// creation of new poll
const poll = new Poll(this.userService.getCurrentUser(), this.uuidService.getUUID(), '');
this._poll.next(poll);
this.router.navigate(['poll/' + poll.custom_url + '/administration']);
}
if ( if (
!this._poll.getValue() || !this._poll.getValue() ||
!this._poll.getValue().custom_url || !this._poll.getValue().custom_url ||
@ -94,6 +88,8 @@ export class PollService implements Resolve<Poll> {
} else { } else {
this.toastService.display(`sondage ${custom_url} non trouvé`); this.toastService.display(`sondage ${custom_url} non trouvé`);
} }
} else {
this.toastService.display(`sondage sans custom url : ${custom_url}`);
} }
} }

View File

@ -103,6 +103,11 @@ export class StorageService {
return false; return false;
} }
/**
* set all time slices of a choice to the same answer at once
* @param groupe
* @param newAnswer
*/
setAllSubchoicesTo(groupe, newAnswer = 'yes') { setAllSubchoicesTo(groupe, newAnswer = 'yes') {
groupe.choices.map((choice) => { groupe.choices.map((choice) => {
for (const vote of this.vote_stack.votes) { for (const vote of this.vote_stack.votes) {
@ -112,4 +117,16 @@ export class StorageService {
} }
}); });
} }
mapVotes(resp) {
console.log('data', resp.data);
console.log('this.vote_stack', this.vote_stack);
this.vote_stack.votes = [];
this.vote_stack.owner = resp.data.owner;
this.vote_stack.id = resp.data.id;
for (const vote of resp.data.votes) {
this.vote_stack.votes.push(vote);
}
console.log('this.vote_stack', this.vote_stack);
}
} }

View File

@ -7,7 +7,10 @@ const routes: Routes = [
{ {
path: '', path: '',
component: ConsultationComponent, component: ConsultationComponent,
children: [{ path: '/:hash', component: ConsultationComponent }], children: [
{ path: '/', component: ConsultationComponent },
{ path: '/:pass_hash', component: ConsultationComponent },
],
}, },
]; ];
@NgModule({ @NgModule({

View File

@ -118,4 +118,9 @@
</div> </div>
</div> </div>
</div> </div>
<pre class="debug padded warning">
storageService.vote_stack :
{{ storageService.vote_stack | json }}
</pre
>
</section> </section>

View File

@ -1,5 +1,5 @@
import { Component, OnDestroy, OnInit } from '@angular/core'; import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, ParamMap, Router } from '@angular/router';
import { Subscription } from 'rxjs'; import { Subscription } from 'rxjs';
import { Poll } from '../../core/models/poll.model'; import { Poll } from '../../core/models/poll.model';
import { ModalService } from '../../core/services/modal.service'; import { ModalService } from '../../core/services/modal.service';
@ -11,6 +11,8 @@ import { ApiService } from '../../core/services/api.service';
import { Stack } from '../../core/models/stack.model'; import { Stack } from '../../core/models/stack.model';
import { environment } from '../../../environments/environment'; import { environment } from '../../../environments/environment';
import { ToastService } from '../../core/services/toast.service'; import { ToastService } from '../../core/services/toast.service';
import { AxiosResponse } from 'axios';
import { HttpResponse } from '@angular/common/http';
@Component({ @Component({
selector: 'app-consultation', selector: 'app-consultation',
@ -45,6 +47,9 @@ export class ConsultationComponent implements OnInit, OnDestroy {
public toastService: ToastService public toastService: ToastService
) {} ) {}
/**
* fetch poll data on init
*/
ngOnInit(): void { ngOnInit(): void {
console.log('constultation de poll'); console.log('constultation de poll');
this.pollService.poll.subscribe((newpoll: Poll) => { this.pollService.poll.subscribe((newpoll: Poll) => {
@ -56,19 +61,19 @@ export class ConsultationComponent implements OnInit, OnDestroy {
} }
}); });
this._Activatedroute.paramMap.subscribe((params) => { this._Activatedroute.paramMap.subscribe((params: ParamMap) => {
console.log('params', params); console.log('params _Activatedroute', params);
this.pollSlug = params.get('slug'); this.pollSlug = params.get('custom_url');
this.passHash = params.get('hash'); this.passHash = params.get('pass_hash');
if (this.passHash) { // if (this.passHash) {
this.pollService.loadPollBycustom_urlWithPasswordHash(this.pollSlug, this.passHash); // this.pollService.loadPollBycustom_urlWithPasswordHash(this.pollSlug, this.passHash);
} else { // } else {
this.pollService.loadPollBycustom_url(this.pollSlug).then((resp) => { this.pollService.loadPollBycustom_url(this.pollSlug).then((resp) => {
console.log('resp', resp); console.log('resp', resp);
this.fetching = false; this.fetching = false;
}); });
} // }
}); });
} }
@ -78,22 +83,49 @@ export class ConsultationComponent implements OnInit, OnDestroy {
} }
} }
/**
* update existing vote stack
* @param vote_stack
*/
updateVoteStack(vote_stack: Stack): void { updateVoteStack(vote_stack: Stack): void {
alert('TODO'); vote_stack.poll_custom_url = this.poll.custom_url;
// const handlingError = this.api.handleError;
this.api.sendUpdateVoteStack(vote_stack).then((resp) => { this.api.sendUpdateVoteStack(vote_stack).then((resp) => {
console.log('sendUpdateVoteStack resp', resp); console.log('sendUpdateVoteStack resp', resp);
this.storeVoteStackAndReloadPoll(resp);
this.toastService.display('vote bien mis à jour', 'success'); this.toastService.display('vote bien mis à jour', 'success');
}); });
// .catch(handlingError);
} }
/**
* create a new vote stack
*/
addVoteStack(): void { addVoteStack(): void {
this.toastService.display('envoi du vote ....'); this.storageService.vote_stack.poll_custom_url = this.poll.custom_url;
this.api.sendNewVoteStackOfPoll(this.poll, this.storageService.vote_stack).then((resp) => {
console.log('resp', resp);
this.pollService.loadPollBycustom_url(this.poll.custom_url); this.toastService.display('envoi du vote ....');
this.api.sendNewVoteStackOfPoll(this.storageService.vote_stack).then((resp: any) => {
console.log('sendNewVoteStackOfPoll resp', resp);
this.storeVoteStackAndReloadPoll(resp);
}); });
// eslint-disable-next-line @typescript-eslint/unbound-method
// .catch(this.api.handleError);
}
/**
* store the updated vote stack
* @param voteStack
*/
storeVoteStackAndReloadPoll(voteStack: any) {
if (voteStack.status == 200) {
this.storageService.mapVotes(voteStack);
this.pollService.loadPollBycustom_url(this.poll.custom_url);
} else {
this.toastService.display('erreur à l enregistrement');
}
} }
/** /**

View File

@ -31,12 +31,12 @@ export const routes: Routes = [
{ {
path: 'poll/:custom_url/consultation', path: 'poll/:custom_url/consultation',
loadChildren: () => import('./features/consultation/consultation.module').then((m) => m.ConsultationModule), loadChildren: () => import('./features/consultation/consultation.module').then((m) => m.ConsultationModule),
resolve: { poll: PollService }, // resolve: { poll: PollService },
}, },
{ {
path: 'poll/:custom_url/participation', path: 'poll/:custom_url/participation',
loadChildren: () => import('./features/participation/participation.module').then((m) => m.ParticipationModule), loadChildren: () => import('./features/participation/participation.module').then((m) => m.ParticipationModule),
// resolve: { poll: PollService }, resolve: { poll: PollService },
}, },
{ {
path: 'success', path: 'success',

View File

@ -28,7 +28,7 @@
</div> </div>
</article> </article>
</section> </section>
<section class="add-comment" *ngIf="!poll.is_archived"> <section class="add-comment" *ngIf="!poll.is_archived && vote_stack.owner">
<h2 class="margin-top-x7">Laisser un commentaire</h2> <h2 class="margin-top-x7">Laisser un commentaire</h2>
<article class="message"> <article class="message">
<div class="message-header"> <div class="message-header">

View File

@ -1,6 +1,6 @@
export const backendApiUrlsInDev = { export const backendApiUrlsInDev = {
local: 'http://tktest.lan/api/v1', local: 'http://localhost:8000/api/v1',
remote: 'http://tktest.lan/api/v1', remote: 'http://localhost:8000/api/v1',
// remote: 'https://framadate-api.cipherbliss.com/api/v1', // remote: 'https://framadate-api.cipherbliss.com/api/v1',
}; };
export const apiV1 = { export const apiV1 = {