import { HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Poll } from '../models/poll.model'; import { Comment } from '../models/comment.model'; @Injectable({ providedIn: 'root', }) export class PollUtilitiesService { // utils functions /** * generate unique id to have a default url for future poll */ makeUuid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { const r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; return v.toString(16); }); } /** * make a uniq custom_url for the current poll creation * @param str */ makeSlug(config: Poll) { let str = ''; const creation = new Date(config.creation_date); str = creation.getFullYear() + '_' + (creation.getMonth() + 1) + '_' + creation.getDate() + '_' + config.creatorPseudo + '_' + config.title; return this.makeSlugFromString(str); } makeSlugFromString(text: string): string { let str = text.replace(/^\s+|\s+$/g, ''); // trim str = str.toLowerCase(); // remove accents, swap ñ for n, etc const from = 'àáäâèéëêìíïîòóöôùúüûñç·/_,:;'; const to = 'aaaaeeeeiiiioooouuuunc------'; for (let 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; } /** * prepare headers like the charset and json type for any call to the backend * @param bodyContent */ makeHeaders(bodyContent?: any) { // const headerDict = { // Charset: 'UTF-8', // 'Content-Type': 'application/json', // Accept: 'application/json', // 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', // 'Access-Control-Allow-Origin': '*', // }; return { headers: [], body: bodyContent, }; } exportCSV(poll: Poll): void { let rows = []; const now = new Date(); const headers = [ ['export de sondage Framadate ', poll.custom_url], ['le', now.toISOString()], [poll.id, poll.title, poll.custom_url, poll.creation_date], ['pseudo'], ]; const listOfChoices = ['choices : ']; poll.choices.map((choice) => { listOfChoices.push(choice.name); }); listOfChoices.push('pseudo'); poll.stacks.map((voteStack) => { const voteStackInArray = [voteStack.pseudo]; const keysVotes = Object.keys(voteStack.votes); keysVotes.map((id) => { voteStackInArray.push(voteStack.votes[id].value ? voteStack.votes[id].value : ''); }); rows.push(voteStackInArray); }); const headersComments = [['comments'], ['pseudo', 'text', 'creation_date']]; const comments = []; poll.comments.map((item: Comment) => { comments.push([item.pseudo, item.text, new Date(item.created_at), '\n']); }); headers.push(listOfChoices); rows = [headers, listOfChoices, rows, headersComments, comments]; const convertedCsv = rows .map((elem) => { console.log('elem', elem); return elem .map((item) => { console.log('item', item); if (typeof item === typeof Array) { return item.join('\n'); } return item; }) .join('\n'); }) .join('\n'); console.log('rows', rows); console.log('convertedCsv', convertedCsv); const csvContent = 'data:text/csv;charset=utf-8,' + convertedCsv; console.log('csvContent', csvContent); const encodedUri = encodeURI(csvContent); const link = document.createElement('a'); link.setAttribute('href', encodedUri); const exportFileName = (poll.custom_url ? poll.custom_url : this.makeSlug(poll)) + '_export_' + new Date() + '.csv'; link.setAttribute('download', exportFileName); document.body.appendChild(link); // Required for FF link.click(); // This will download the data file named "my_data.csv". } download(filename: string, text: string): void { const element = document.createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); element.setAttribute('download', filename); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); } }