forked from LAB-MI/deplacement-covid-19
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcertificate.js
257 lines (210 loc) · 7 KB
/
certificate.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import 'bootstrap/dist/css/bootstrap.min.css'
import { PDFDocument, StandardFonts } from 'pdf-lib'
import QRCode from 'qrcode'
import pdfBase from './certificate.pdf'
import './main.css'
const $ = (...args) => document.querySelector(...args)
const $$ = (...args) => [...document.querySelectorAll(...args)]
var year, month, day
const generateQR = async text => {
try {
var opts = {
errorCorrectionLevel: 'M',
type: 'image/png',
quality: 0.92,
margin: 1,
}
return await QRCode.toDataURL(text, opts)
} catch (err) {
console.error(err)
}
}
function pad (str) {
return String(str).padStart(2, '0')
}
function setDateNow (date) {
year = date.getFullYear()
month = pad(date.getMonth() + 1) // Les mois commencent à 0
day = pad(date.getDate())
}
document.addEventListener('DOMContentLoaded', setReleaseDateTime)
function setReleaseDateTime () {
const loadedDate = new Date()
setDateNow(loadedDate)
const releaseDateInput = document.querySelector('#field-datesortie')
releaseDateInput.value = `${year}-${month}-${day}`
const hour = pad(loadedDate.getHours())
const minute = pad(loadedDate.getMinutes())
const releaseTimeInput = document.querySelector('#field-heuresortie')
releaseTimeInput.value = `${hour}:${minute}`
}
function saveProfile () {
for (const field of $$('#form-profile input')) {
if (field.id === 'field-datesortie') {
var dateSortie = field.value.split('-')
localStorage.setItem(field.id.substring('field-'.length), `${dateSortie[2]}/${dateSortie[1]}/${dateSortie[0]}`)
} else {
localStorage.setItem(field.id.substring('field-'.length), field.value)
}
}
}
function getProfile () {
const fields = {}
for (let i = 0; i < localStorage.length; i++) {
const name = localStorage.key(i)
fields[name] = localStorage.getItem(name)
}
return fields
}
function idealFontSize (font, text, maxWidth, minSize, defaultSize) {
let currentSize = defaultSize
let textWidth = font.widthOfTextAtSize(text, defaultSize)
while (textWidth > maxWidth && currentSize > minSize) {
textWidth = font.widthOfTextAtSize(text, --currentSize)
}
return (textWidth > maxWidth) ? null : currentSize
}
async function generatePdf (profile, reasons) {
const generatedDate = new Date()
setDateNow(generatedDate)
const creationDate = `${day}/${month}/${year}`
const hour = pad(generatedDate.getHours())
const minute = pad(generatedDate.getMinutes())
const creationHour = `${hour}h${minute}`
const { lastname, firstname, birthday, lieunaissance, address, zipcode, town, datesortie, heuresortie } = profile
const releaseHours = String(heuresortie).substring(0, 2)
const releaseMinutes = String(heuresortie).substring(3, 5)
const data = [
`Cree le: ${creationDate} a ${creationHour}`,
`Nom: ${lastname}`,
`Prenom: ${firstname}`,
`Naissance: ${birthday} a ${lieunaissance}`,
`Adresse: ${address} ${zipcode} ${town}`,
`Sortie: ${datesortie} a ${releaseHours}h${releaseMinutes}`,
`Motifs: ${reasons}`,
].join('; ')
const existingPdfBytes = await fetch(pdfBase).then(res => res.arrayBuffer())
const pdfDoc = await PDFDocument.load(existingPdfBytes)
const page1 = pdfDoc.getPages()[0]
const font = await pdfDoc.embedFont(StandardFonts.Helvetica)
const drawText = (text, x, y, size = 11) => {
page1.drawText(text, { x, y, size, font })
}
drawText(`${firstname} ${lastname}`, 123, 686)
drawText(birthday, 123, 661)
drawText(lieunaissance, 92, 638)
drawText(`${address} ${zipcode} ${town}`, 134, 613)
if (reasons.includes('travail')) {
drawText('x', 76, 527, 19)
}
if (reasons.includes('courses')) {
drawText('x', 76, 478, 19)
}
if (reasons.includes('sante')) {
drawText('x', 76, 436, 19)
}
if (reasons.includes('famille')) {
drawText('x', 76, 400, 19)
}
if (reasons.includes('sport')) {
drawText('x', 76, 345, 19)
}
if (reasons.includes('judiciaire')) {
drawText('x', 76, 298, 19)
}
if (reasons.includes('missions')) {
drawText('x', 76, 260, 19)
}
let locationSize = idealFontSize(font, profile.town, 83, 7, 11)
if (!locationSize) {
alert('Le nom de la ville risque de ne pas être affiché correctement en raison de sa longueur. ' +
'Essayez d\'utiliser des abréviations ("Saint" en "St." par exemple) quand cela est possible.')
locationSize = 7
}
drawText(profile.town, 111, 226, locationSize)
if (reasons !== '') {
// Date sortie
drawText(`${profile.datesortie}`, 92, 200)
drawText(releaseHours, 200, 201)
drawText(releaseMinutes, 220, 201)
}
// Date création
drawText('Date de création:', 464, 150, 7)
drawText(`${creationDate} à ${creationHour}`, 455, 144, 7)
const generatedQR = await generateQR(data)
const qrImage = await pdfDoc.embedPng(generatedQR)
page1.drawImage(qrImage, {
x: page1.getWidth() - 170,
y: 155,
width: 100,
height: 100,
})
pdfDoc.addPage()
const page2 = pdfDoc.getPages()[1]
page2.drawImage(qrImage, {
x: 50,
y: page2.getHeight() - 350,
width: 300,
height: 300,
})
const pdfBytes = await pdfDoc.save()
return new Blob([pdfBytes], { type: 'application/pdf' })
}
function downloadBlob (blob, fileName) {
const link = document.createElement('a')
var url = URL.createObjectURL(blob)
link.href = url
link.download = fileName
document.body.appendChild(link)
link.click()
}
function getAndSaveReasons () {
const values = $$('input[name="field-reason"]:checked')
.map(x => x.value)
.join('-')
localStorage.setItem('reasons', values)
return values
}
// see: https://stackoverflow.com/a/32348687/1513045
function isFacebookBrowser () {
const ua = navigator.userAgent || navigator.vendor || window.opera
return ua.includes('FBAN') || ua.includes('FBAV')
}
if (isFacebookBrowser()) {
$('#alert-facebook').classList.remove('d-none')
}
function addSlash () {
this.value = this.value.replace(/^(\d{2})$/g, '$1/')
this.value = this.value.replace(/^(\d{2})\/(\d{2})$/g, '$1/$2/')
}
$('#field-birthday').addEventListener('keyup', addSlash)
const snackbar = $('#snackbar')
$('#form-profile').addEventListener('submit', async event => {
event.preventDefault()
saveProfile()
const reasons = getAndSaveReasons()
const pdfBlob = await generatePdf(getProfile(), reasons)
downloadBlob(pdfBlob, 'attestation.pdf')
snackbar.classList.remove('d-none')
setTimeout(() => snackbar.classList.add('show'), 100)
setTimeout(function () {
snackbar.classList.remove('show')
setTimeout(() => snackbar.classList.add('d-none'), 500)
}, 6000)
})
$$('input').forEach(input => {
const exempleElt = input.parentNode.parentNode.querySelector('.exemple')
if (input.placeholder && exempleElt) {
input.addEventListener('input', (event) => {
if (input.value) {
exempleElt.innerHTML = 'ex. : ' + input.placeholder
} else {
exempleElt.innerHTML = ''
}
})
}
})
function addVersion () {
document.getElementById('version').innerHTML = `${new Date().getFullYear()} - ${process.env.VERSION}`
}
addVersion()