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 polls: Poll[] = [],
public role?: UserRole,
public token?: string
public modifier_token?: string
) {}
}

View File

@ -3,6 +3,7 @@ import { Owner } from './owner.model';
export class Stack {
public id: number;
public poll_custom_url: string;
public pseudo = 'Choque Nourrice';
public comment = 'Le beau commentaire de Choque Nourrice';
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> {
// this.loaderService.setStatus(true);
console.log('createPoll config', poll);
@ -111,17 +90,16 @@ export class ApiService {
/**
* send a new vote stack
* @param poll
* @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
console.log('vote_stack', vote_stack);
console.log('this.baseHref', this.baseHref);
const headers = ApiService.makeHeaders(vote_stack);
console.log('headers', headers);
const url = `${this.baseHref}/vote/poll/${poll.custom_url}/answer`;
const url = `${this.baseHref}/vote-stack/`;
const axiosconf = {
url,
@ -174,8 +152,8 @@ export class ApiService {
public async getPollByCustomUrl(slug: string): Promise<Poll | undefined> {
try {
console.log('fetch API : asking for poll with custom_url=' + 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;
} catch (error) {
@ -227,7 +205,10 @@ export class ApiService {
public async sendUpdateVoteStack(vote_stack: Stack) {
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) {
ApiService.handleError(error);
}
@ -286,4 +267,24 @@ export class ApiService {
/////////////////////
// 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
*/
public async resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<Poll> {
console.log('resolve route,state', route, state);
const segments: string[] = state.url.split('/');
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 (
!this._poll.getValue() ||
!this._poll.getValue().custom_url ||
@ -94,6 +88,8 @@ export class PollService implements Resolve<Poll> {
} else {
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;
}
/**
* set all time slices of a choice to the same answer at once
* @param groupe
* @param newAnswer
*/
setAllSubchoicesTo(groupe, newAnswer = 'yes') {
groupe.choices.map((choice) => {
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: '',
component: ConsultationComponent,
children: [{ path: '/:hash', component: ConsultationComponent }],
children: [
{ path: '/', component: ConsultationComponent },
{ path: '/:pass_hash', component: ConsultationComponent },
],
},
];
@NgModule({

View File

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

View File

@ -1,5 +1,5 @@
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 { Poll } from '../../core/models/poll.model';
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 { environment } from '../../../environments/environment';
import { ToastService } from '../../core/services/toast.service';
import { AxiosResponse } from 'axios';
import { HttpResponse } from '@angular/common/http';
@Component({
selector: 'app-consultation',
@ -45,6 +47,9 @@ export class ConsultationComponent implements OnInit, OnDestroy {
public toastService: ToastService
) {}
/**
* fetch poll data on init
*/
ngOnInit(): void {
console.log('constultation de poll');
this.pollService.poll.subscribe((newpoll: Poll) => {
@ -56,19 +61,19 @@ export class ConsultationComponent implements OnInit, OnDestroy {
}
});
this._Activatedroute.paramMap.subscribe((params) => {
console.log('params', params);
this.pollSlug = params.get('slug');
this.passHash = params.get('hash');
this._Activatedroute.paramMap.subscribe((params: ParamMap) => {
console.log('params _Activatedroute', params);
this.pollSlug = params.get('custom_url');
this.passHash = params.get('pass_hash');
if (this.passHash) {
this.pollService.loadPollBycustom_urlWithPasswordHash(this.pollSlug, this.passHash);
} else {
this.pollService.loadPollBycustom_url(this.pollSlug).then((resp) => {
console.log('resp', resp);
this.fetching = false;
});
}
// if (this.passHash) {
// this.pollService.loadPollBycustom_urlWithPasswordHash(this.pollSlug, this.passHash);
// } else {
this.pollService.loadPollBycustom_url(this.pollSlug).then((resp) => {
console.log('resp', resp);
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 {
alert('TODO');
vote_stack.poll_custom_url = this.poll.custom_url;
// const handlingError = this.api.handleError;
this.api.sendUpdateVoteStack(vote_stack).then((resp) => {
console.log('sendUpdateVoteStack resp', resp);
this.storeVoteStackAndReloadPoll(resp);
this.toastService.display('vote bien mis à jour', 'success');
});
// .catch(handlingError);
}
/**
* create a new vote stack
*/
addVoteStack(): void {
this.toastService.display('envoi du vote ....');
this.api.sendNewVoteStackOfPoll(this.poll, this.storageService.vote_stack).then((resp) => {
console.log('resp', resp);
this.storageService.vote_stack.poll_custom_url = this.poll.custom_url;
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',
loadChildren: () => import('./features/consultation/consultation.module').then((m) => m.ConsultationModule),
resolve: { poll: PollService },
// resolve: { poll: PollService },
},
{
path: 'poll/:custom_url/participation',
loadChildren: () => import('./features/participation/participation.module').then((m) => m.ParticipationModule),
// resolve: { poll: PollService },
resolve: { poll: PollService },
},
{
path: 'success',

View File

@ -28,7 +28,7 @@
</div>
</article>
</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>
<article class="message">
<div class="message-header">

View File

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