· 8 years ago · Mar 04, 2018, 07:50 AM
1'use strict'
2
3// Dependencies
4
5const bodyParser = require('body-parser')
6const compression = require('compression')
7const express = require('express')
8var fileUpload = require('express-fileupload')
9var mysql = require('mysql')
10var session = require('express-session')
11
12// Configuration
13
14process.env.NODE_ENV = 'production'
15
16const app = express()
17app.set('view engine', 'ejs')
18app.use(bodyParser.urlencoded({ extended: false })) // parse application/x-www-form-urlencoded
19app.use(compression())
20app.use(express.static(__dirname + '/email'))
21app.use(express.static(__dirname + '/public'))
22app.use(fileUpload())
23app.use(session({
24 secret: 'NnnstJ4#qzRn9*saaZ5a*@#^3rxPdF',
25 resave: false,
26 saveUninitialized: true
27}))
28
29if (app.get('env') === 'production') {
30 app.set('trust proxy', 1) // trust first proxy
31 // session.cookie.secure = true // serve secure cookies
32}
33
34// Database connection
35
36var connection = mysql.createConnection({
37 host: 'localhost',
38 user: 'kuntokes_energy',
39 password: '2VPy9cp6bSNN78UU%hzr*wr5Mt!n%q',
40 database: 'kuntokes_energy'
41})
42
43// Global functions
44
45function checkIfBranchExists (res, branch, callback) {
46 connection.query('SELECT nimi_ilman_skandeja FROM branches WHERE nimi_ilman_skandeja = "' + branch + '"', function (error, results, fields) {
47 if (error) throw error
48 if (typeof results[0] === 'undefined') {
49 res.status(404).render('404.ejs')
50 } else {
51 callback()
52 }
53 })
54}
55
56// Routes
57
58app.get('/', function (req, res) {
59 var backgroundImage = ''
60 var navigationData = []
61 var notification = ''
62 var partners = ''
63
64 var inEnglish = false
65 if (req.query.lang === 'en') {
66 inEnglish = true
67 }
68
69 fetchInformationForNavigation()
70
71 function fetchInformationForNavigation () {
72 connection.query('SELECT nimi, nimi_ilman_skandeja FROM branches', function (error, results, fields) {
73 if (error) throw error
74 navigationData = results
75 fetchNotification()
76 })
77 }
78
79 function fetchNotification () {
80 connection.query('SELECT internet_osoite FROM frontpage WHERE tyyppi = "frontpage-notification" OR tyyppi = "frontpage-notification-eng"', function (error, results, fields) {
81 if (error) throw error
82 if (inEnglish) {
83 notification = results[1].internet_osoite
84 } else {
85 notification = results[0].internet_osoite
86 }
87 fetchPartners()
88 })
89 }
90
91 function fetchPartners () {
92 connection.query('SELECT internet_osoite, kuva FROM frontpage WHERE tyyppi = "frontpage-partner"', function (error, results, fields) {
93 if (error) throw error
94 partners = results
95 fetchFrontPageImage()
96 })
97 }
98
99 function fetchFrontPageImage () {
100 connection.query('SELECT kuva FROM frontpage WHERE tyyppi = "frontpage-image"', function (error, results, fields) {
101 if (error) throw error
102 backgroundImage = results[0].kuva
103 renderView()
104 })
105 }
106
107 function renderView () {
108 res.render('frontpage.ejs', {
109 backgroundImage: backgroundImage,
110 inEnglish: inEnglish,
111 navigationData: navigationData,
112 notification: notification,
113 partners: partners
114 })
115 }
116})
117
118app.get('/fysioterapia/:branch', function (req, res) {
119 // Check if branch exists before proceeding
120 var branch = req.params.branch
121 checkIfBranchExists(res, branch, fetchInformationForNavigation)
122
123 // Variables
124 var contactInfo = ''
125 var galleryItems = ''
126 var heading = ''
127 var inEnglish = false
128 var latitude = ''
129 var location = ''
130 var longitude = ''
131 var navigationData = []
132 var openingTimes = ''
133 var physiotherapyServices = ''
134 var staffMembers = ''
135 var subHeading = ''
136 var urlEncodedName = ''
137
138 if (req.query.lang === 'en') {
139 inEnglish = true
140 }
141
142 function fetchInformationForNavigation () {
143 connection.query('SELECT nimi, nimi_ilman_skandeja FROM branches', function (error, results, fields) {
144 if (error) throw error
145 navigationData = results
146 fetchBranchInformation()
147 })
148 }
149
150 function fetchBranchInformation () {
151 connection.query('SELECT nimi_ilman_skandeja, fysioterapia_otsikko, fysioterapia_otsikko_eng, fysioterapia_alaotsikko, fysioterapia_alaotsikko_eng, koordinaatti_leveys, koordinaatti_pituus, aukioloajat, aukioloajat_eng, yhteystiedot, yhteystiedot_eng, sijainti, sijainti_eng FROM branches WHERE nimi_ilman_skandeja = "' + branch + '"', function (error, results, fields) {
152 if (error) throw error
153 contactInfo = inEnglish ? results[0].yhteystiedot_eng : results[0].yhteystiedot
154 heading = inEnglish ? results[0].fysioterapia_otsikko_eng : results[0].fysioterapia_otsikko
155 latitude = results[0].koordinaatti_leveys
156 location = inEnglish ? results[0].sijainti_eng : results[0].sijainti
157 longitude = results[0].koordinaatti_pituus
158 openingTimes = inEnglish ? results[0].aukioloajat_eng : results[0].aukioloajat
159 subHeading = inEnglish ? results[0].fysioterapia_alaotsikko_eng : results[0].fysioterapia_alaotsikko
160 urlEncodedName = results[0].nimi_ilman_skandeja
161 fetchServiceDescriptions()
162 })
163 }
164
165 function fetchServiceDescriptions () {
166 connection.query('SELECT kuva, palvelun_nimi, palvelun_nimi_eng, palvelun_kuvaus, palvelun_kuvaus_eng, videon_osoite FROM physiotherapy_services WHERE ' + branch + ' = "kyllä" ORDER by jarjestys', function (error, results, fields) {
167 if (error) throw error
168 physiotherapyServices = results
169 fetchStaffMembers()
170 })
171 }
172
173 function fetchStaffMembers () {
174 connection.query('SELECT kuvausteksti, kuva, nimi, titteli, titteli_eng, ajanvarauskalenterin_osoite FROM staff WHERE ' + urlEncodedName + ' = "kyllä" AND titteli LIKE "%Fysiotera%" ORDER BY rand()', function (error, results, fields) {
175 if (error) throw error
176 staffMembers = results
177 renderView()
178 })
179 }
180
181 function renderView () {
182 res.render('physiotherapy.ejs', {
183 branch: branch,
184 contactInfo: contactInfo,
185 galleryItems: galleryItems,
186 heading: heading,
187 heroButtonText: '',
188 heroButtonURL: '',
189 inEnglish: inEnglish,
190 latitude: latitude,
191 location: location,
192 longitude: longitude,
193 navigationData: navigationData,
194 openingTimes: openingTimes,
195 physiotherapyServices: physiotherapyServices,
196 staffMembers: staffMembers,
197 subHeading: subHeading
198 })
199 }
200})
201
202app.get('/maps', function (req, res) {
203 res.render('partials/google-maps.ejs', {
204 longitude: req.query.screencenter.longitude,
205 latitude: req.query.screencenter.latitude
206 })
207})
208
209app.get('/hieronta/:branch', function (req, res) {
210 // Check if branch exists before proceeding
211 var branch = req.params.branch
212 var inEnglish = false
213 if (req.query.lang === 'en') {
214 inEnglish = true
215 }
216 checkIfBranchExists(res, branch, fetchInformationForNavigation)
217
218 // Variables
219 var contactInfo = ''
220 var galleryItems = ''
221 var heading = ''
222 var latitude = ''
223 var location = ''
224 var longitude = ''
225 var massageServices = ''
226 var navigationData = []
227 var openingTimes = ''
228 var staffMembers = ''
229 var subHeading = ''
230 var urlEncodedName = ''
231
232 function fetchInformationForNavigation () {
233 connection.query('SELECT nimi, nimi_ilman_skandeja FROM branches', function (error, results, fields) {
234 if (error) throw error
235 navigationData = results
236 fetchBranchInformation()
237 })
238 }
239
240 function fetchBranchInformation () {
241 connection.query('SELECT nimi_ilman_skandeja, hieronta_otsikko, hieronta_otsikko_eng, hieronta_alaotsikko, hieronta_alaotsikko_eng, koordinaatti_leveys, koordinaatti_pituus, aukioloajat, aukioloajat_eng, yhteystiedot, yhteystiedot_eng, sijainti, sijainti_eng FROM branches WHERE nimi_ilman_skandeja = "' + branch + '"', function (error, results, fields) {
242 if (error) throw error
243 contactInfo = inEnglish ? results[0].yhteystiedot_eng : results[0].yhteystiedot
244 heading = inEnglish ? results[0].hieronta_otsikko_eng : results[0].hieronta_otsikko
245 latitude = results[0].koordinaatti_leveys
246 location = inEnglish ? results[0].sijainti_eng : results[0].sijainti
247 longitude = results[0].koordinaatti_pituus
248 openingTimes = inEnglish ? results[0].aukioloajat_eng : results[0].aukioloajat
249 subHeading = inEnglish ? results[0].hieronta_alaotsikko_eng : results[0].hieronta_alaotsikko
250 urlEncodedName = results[0].nimi_ilman_skandeja
251 fetchServiceDescriptions()
252 })
253 }
254
255 function fetchServiceDescriptions () {
256 connection.query('SELECT kuva, palvelun_nimi, palvelun_nimi_eng, palvelun_kuvaus, palvelun_kuvaus_eng, videon_osoite FROM massage_services WHERE ' + branch + ' = "kyllä" ORDER by jarjestys', function (error, results, fields) {
257 if (error) throw error
258 massageServices = results
259 fetchStaffMembers()
260 })
261 }
262
263 function fetchStaffMembers () {
264 connection.query('SELECT kuvausteksti, kuva, nimi, titteli, titteli_eng, ajanvarauskalenterin_osoite FROM staff WHERE ' + urlEncodedName + ' = "kyllä" AND titteli LIKE "%Hieroja%" ORDER BY rand()', function (error, results, fields) {
265 if (error) throw error
266 staffMembers = results
267 renderView()
268 })
269 }
270
271 function renderView () {
272 res.render('massage.ejs', {
273 branch: branch,
274 contactInfo: contactInfo,
275 galleryItems: galleryItems,
276 heading: heading,
277 heroButtonText: '',
278 heroButtonURL: '',
279 inEnglish: inEnglish,
280 latitude: latitude,
281 location: location,
282 longitude: longitude,
283 massageServices: massageServices,
284 navigationData: navigationData,
285 openingTimes: openingTimes,
286 staffMembers: staffMembers,
287 subHeading: subHeading
288 })
289 }
290})
291
292app.get('/hinnasto', function (req, res) {
293 var contracts = ''
294 var contractsInfo = ''
295 var gymServices = ''
296 var gymServicesInfo = ''
297 var massageServices = ''
298 var massageServicesInfo = ''
299 var navigationData = []
300 var physiotherapyServices = ''
301 var physiotherapyServicesInfo = ''
302
303 var inEnglish = false
304 if (req.query.lang === 'en') {
305 inEnglish = true
306 }
307
308 fetchInformationForNavigation()
309
310 function fetchInformationForNavigation () {
311 connection.query('SELECT nimi, nimi_ilman_skandeja FROM branches', function (error, results, fields) {
312 if (error) throw error
313 navigationData = results
314 fetchContracts()
315 })
316 }
317
318 function fetchContracts () {
319 connection.query('SELECT product, product_eng, price1, price2, price1_eng, price2_eng, description, description_eng FROM prices WHERE section = "sopimukset" ORDER BY jarjestys', function (error, results, fields) {
320 if (error) throw error
321 contracts = results
322 fetchContractInfo()
323 })
324 }
325
326 function fetchContractInfo () {
327 connection.query('SELECT description, description_eng FROM prices WHERE section = "sopimukset_lisatiedot"', function (error, results, fields) {
328 if (error) throw error
329 contractsInfo = results[0]
330 fetchGymServices()
331 })
332 }
333
334 function fetchGymServices () {
335 connection.query('SELECT product, product_eng, price1, price2, price1_eng, price2_eng, description, description_eng, jarjestys FROM prices WHERE section = "kuntosalipalvelut" ORDER BY jarjestys', function (error, results, fields) {
336 if (error) throw error
337 gymServices = results
338 fetchGymServicesInfo()
339 })
340 }
341
342 function fetchGymServicesInfo () {
343 connection.query('SELECT description, description_eng FROM prices WHERE section = "kuntosalipalvelut_lisatiedot"', function (error, results, fields) {
344 if (error) throw error
345 gymServicesInfo = results[0]
346 fetchPhysiotherapyServices()
347 })
348 }
349
350 function fetchPhysiotherapyServices () {
351 connection.query('SELECT product, product_eng, price1, price2, price1_eng, price2_eng, description, description_eng FROM prices WHERE section = "fysioterapiapalvelut" ORDER BY jarjestys', function (error, results, fields) {
352 if (error) throw error
353 physiotherapyServices = results
354 fetchPhysiotherapyServicesInfo()
355 })
356 }
357
358 function fetchPhysiotherapyServicesInfo () {
359 connection.query('SELECT description, description_eng FROM prices WHERE section = "fysioterapiapalvelut_lisatiedot"', function (error, results, fields) {
360 if (error) throw error
361 physiotherapyServicesInfo = results[0]
362 fetchMassageServices()
363 })
364 }
365
366 function fetchMassageServices () {
367 connection.query('SELECT product, product_eng, price1, price2, price1_eng, price2_eng, description, description_eng FROM prices WHERE section = "hierontapalvelut" ORDER BY jarjestys', function (error, results, fields) {
368 if (error) throw error
369 massageServices = results
370 fetchMassageServicesInfo()
371 })
372 }
373
374 function fetchMassageServicesInfo () {
375 connection.query('SELECT description, description_eng FROM prices WHERE section = "hierontapalvelut_lisatiedot"', function (error, results, fields) {
376 if (error) throw error
377 massageServicesInfo = results[0]
378 renderView()
379 })
380 }
381
382 function renderView () {
383 res.render('hinnasto.ejs', {
384 contracts: contracts,
385 contractsInfo: contractsInfo,
386 gymServices: gymServices,
387 gymServicesInfo: gymServicesInfo,
388 inEnglish: inEnglish,
389 massageServices: massageServices,
390 massageServicesInfo: massageServicesInfo,
391 navigationData: navigationData,
392 physiotherapyServices: physiotherapyServices,
393 physiotherapyServicesInfo: physiotherapyServicesInfo
394 })
395 }
396})
397
398app.get('/kuntosali/:branch', function (req, res) {
399 // Check if branch exists before proceeding
400 var branch = req.params.branch
401 var inEnglish = false
402 if (req.query.lang === 'en') {
403 inEnglish = true
404 }
405 checkIfBranchExists(res, branch, fetchInformationForNavigation)
406
407 // Variables
408 var branchName = ''
409 var contactInfo = ''
410 var galleryItems = ''
411 var gymServices = ''
412 var heroImage = ''
413 var latitude = ''
414 var location = ''
415 var longitude = ''
416 var navigationData = ''
417 var openingTimes = ''
418 var staffMembers = ''
419 var subHeading = ''
420 var urlEncodedName = ''
421 var videoURL = ''
422
423 function fetchInformationForNavigation () {
424 connection.query('SELECT nimi, nimi_ilman_skandeja FROM branches', function (error, results, fields) {
425 if (error) throw error
426 navigationData = results
427 fetchBranchInformation()
428 })
429 }
430
431 function fetchBranchInformation () {
432 connection.query('SELECT nimi, nimi_ilman_skandeja, nimi_ilman_skandeja, kuva, kuntosali_alaotsikko, kuntosali_alaotsikko_eng, videon_osoite, koordinaatti_leveys, koordinaatti_pituus, aukioloajat, aukioloajat_eng, yhteystiedot, yhteystiedot_eng, sijainti, sijainti_eng FROM branches WHERE nimi_ilman_skandeja = "' + branch + '"', function (error, results, fields) {
433 if (error) throw error
434 branchName = results[0].nimi
435 contactInfo = inEnglish ? results[0].yhteystiedot_eng : results[0].yhteystiedot
436 heroImage = results[0].kuva
437 latitude = results[0].koordinaatti_leveys
438 location = inEnglish ? results[0].sijainti_eng : results[0].sijainti
439 longitude = results[0].koordinaatti_pituus
440 openingTimes = inEnglish ? results[0].aukioloajat_eng : results[0].aukioloajat
441 subHeading = inEnglish ? results[0].kuntosali_alaotsikko_eng : results[0].kuntosali_alaotsikko
442 urlEncodedName = results[0].nimi_ilman_skandeja
443 videoURL = results[0].videon_osoite
444 fetchgalleryItems()
445 })
446 }
447
448 function fetchgalleryItems () {
449 connection.query('SELECT toimipiste, kuvateksti, kuvateksti_eng, kuva FROM gym_gallery WHERE toimipiste = "' + branch + '" ORDER by jarjestys', function (error, results, fields) {
450 if (error) throw error
451 galleryItems = results
452 fetchServiceDescriptions()
453 })
454 }
455
456 function fetchServiceDescriptions () {
457 connection.query('SELECT kuva, palvelun_nimi, palvelun_nimi_eng, palvelun_kuvaus, palvelun_kuvaus_eng, videon_osoite FROM gym_services WHERE ' + branch + ' = "kyllä" ORDER by jarjestys', function (error, results, fields) {
458 if (error) throw error
459 gymServices = results
460 fetchStaffMembers()
461 })
462 }
463
464 function fetchStaffMembers () {
465 connection.query('SELECT kuvausteksti, kuva, nimi, titteli, titteli_eng, ajanvarauskalenterin_osoite FROM staff WHERE ' + urlEncodedName + ' = "kyllä" AND titteli LIKE "%Personal%" ORDER BY rand()', function (error, results, fields) {
466 if (error) throw error
467 staffMembers = results
468 renderView()
469 })
470 }
471
472 function renderView () {
473 res.render('gym.ejs', {
474 branch: branch,
475 contactInfo: contactInfo,
476 galleryItems: galleryItems,
477 gymServices: gymServices,
478 heading: branchName,
479 heroButtonText: '',
480 heroButtonURL: '',
481 heroImage: heroImage,
482 inEnglish: inEnglish,
483 latitude: latitude,
484 location: location,
485 longitude: longitude,
486 navigationData: navigationData,
487 openingTimes: openingTimes,
488 staffMembers: staffMembers,
489 subHeading: subHeading,
490 videoURL: videoURL
491 })
492 }
493})
494
495app.get('/ryhmaliikunta/:branch', function (req, res) {
496 // Check if branch exists before proceeding
497 var branch = req.params.branch
498 var inEnglish = false
499 if (req.query.lang === 'en') {
500 inEnglish = true
501 }
502 checkIfBranchExists(res, branch, fetchInformationForNavigation)
503
504 // Variables
505 var branchName = ''
506 var calendarBackgrounds = []
507 var classDescriptions = []
508 var contactInfo = ''
509 var groupExerciseCalendarItemsRaw = []
510 var groupExerciseItems = []
511 var heading = ''
512 var latitude = ''
513 var location = ''
514 var longitude = ''
515 var navigationData = []
516 var openingTimes = ''
517 var spinningCalendarItemsRaw = []
518 var spinningItems = []
519 var staffMembers = []
520 var subHeading = ''
521 var urlEncodedName = ''
522
523 function fetchInformationForNavigation () {
524 connection.query('SELECT nimi, nimi_ilman_skandeja FROM branches', function (error, results, fields) {
525 if (error) throw error
526 navigationData = results
527 fetchBranchInformation()
528 })
529 }
530
531 function fetchBranchInformation () {
532 connection.query('SELECT nimi, nimi_ilman_skandeja, ryhmaliikunta_otsikko, ryhmaliikunta_otsikko_eng, ryhmaliikunta_alaotsikko, ryhmaliikunta_alaotsikko_eng, koordinaatti_leveys, koordinaatti_pituus, aukioloajat, aukioloajat_eng, yhteystiedot, yhteystiedot_eng, sijainti, sijainti_eng FROM branches WHERE nimi_ilman_skandeja = "' + branch + '"', function (error, results, fields) {
533 if (error) throw error
534 branchName = results[0].nimi
535 contactInfo = inEnglish ? results[0].yhteystiedot_eng : results[0].yhteystiedot
536 heading = inEnglish ? results[0].ryhmaliikunta_otsikko_eng : results[0].ryhmaliikunta_otsikko
537 latitude = results[0].koordinaatti_leveys
538 location = inEnglish ? results[0].sijainti_eng : results[0].sijainti
539 longitude = results[0].koordinaatti_pituus
540 openingTimes = inEnglish ? results[0].aukioloajat_eng : results[0].aukioloajat
541 subHeading = inEnglish ? results[0].ryhmaliikunta_alaotsikko_eng : results[0].ryhmaliikunta_alaotsikko
542 urlEncodedName = results[0].nimi_ilman_skandeja
543 fetchGroupExerciseCalendarBackgrounds()
544 })
545 }
546
547 function fetchGroupExerciseCalendarBackgrounds () {
548 connection.query('SELECT kuva, tyyppi FROM group_exercise_calendar_backgrounds WHERE toimipiste = "' + branch + '"', function (error, results, fields) {
549 if (error) throw error
550 for (var i = 0; i < results.length; i++) {
551 if (typeof results[i] !== 'undefined' && results[i].tyyppi === 'ryhmaliikunta') {
552 calendarBackgrounds.ryhmaliikunta = results[i].kuva
553 }
554 if (typeof results[i] !== 'undefined' && results[i].tyyppi === 'spinning') {
555 calendarBackgrounds.spinning = results[i].kuva
556 }
557 }
558 fetchGroupExerciseCalendarItems()
559 })
560 }
561
562 function fetchGroupExerciseCalendarItems () {
563 connection.query('SELECT paiva, tunnin_aika_nimi_ja_ohjaaja FROM group_exercise_calendar WHERE toimipiste = "' + branch + '" AND tyyppi = "ryhmaliikunta"', function (error, results, fields) {
564 if (error) throw error
565 groupExerciseCalendarItemsRaw = results
566 fetchSpinningCalendarItems()
567 })
568 }
569
570 function fetchSpinningCalendarItems () {
571 connection.query('SELECT paiva, tunnin_aika_nimi_ja_ohjaaja FROM group_exercise_calendar WHERE toimipiste = "' + branch + '" AND tyyppi = "spinning"', function (error, results, fields) {
572 if (error) throw error
573 spinningCalendarItemsRaw = results
574 fetchClassDescriptions()
575 })
576 }
577
578 function fetchClassDescriptions () {
579 connection.query('SELECT kuva, tunnin_nimi, tunnin_kuvaus, tunnin_kuvaus_eng, videon_osoite, centrum, rantakyla, ylamylly FROM group_exercise_classes WHERE ' + branch + ' = "kyllä" ORDER BY tunnin_nimi', function (error, results, fields) {
580 if (error) throw error
581 classDescriptions = results
582 fetchStaffMembers()
583 })
584 }
585
586 function fetchStaffMembers () {
587 connection.query('SELECT kuvausteksti, kuva, nimi, titteli, titteli_eng, ajanvarauskalenterin_osoite FROM staff WHERE ' + urlEncodedName + ' = "kyllä" AND titteli LIKE "%Ryhmäliikun%" ORDER BY rand()', function (error, results, fields) {
588 if (error) throw error
589 staffMembers = results
590 organizeCalendarItems(groupExerciseCalendarItemsRaw, groupExerciseItems)
591 organizeCalendarItems(spinningCalendarItemsRaw, spinningItems)
592 renderView()
593 })
594 }
595
596 function organizeCalendarItems (calendarItemsRaw, calendarItems) {
597 var daysOfTheWeek = ['maanantai', 'tiistai', 'keskiviikko', 'torstai', 'perjantai', 'lauantai', 'sunnuntai']
598 var daysOfTheWeekLANG = []
599 if (inEnglish) {
600 daysOfTheWeekLANG = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
601 } else {
602 daysOfTheWeekLANG = ['Maanantai', 'Tiistai', 'Keskiviikko', 'Torstai', 'Perjantai', 'Lauantai', 'Sunnuntai']
603 }
604
605 // Create arrays to hold items for each day and give each day a heading
606 for (var i = 0; i < daysOfTheWeekLANG.length; i++) {
607 calendarItems.push(new Array(daysOfTheWeekLANG[i]))
608 }
609
610 // Populate the arrays with classes for each day
611 for (i = 0; i < calendarItemsRaw.length; i++) {
612 for (var ii = 0; ii < daysOfTheWeek.length; ii++) {
613 if (calendarItemsRaw[i].paiva === daysOfTheWeek[ii]) {
614 calendarItems[ii].push(calendarItemsRaw[i].tunnin_aika_nimi_ja_ohjaaja)
615 }
616 }
617 }
618
619 // Check which days do not have classes
620 var daysToBeRemoved = []
621 for (i = 0; i < calendarItems.length; i++) {
622 if (calendarItems[i].length === 1) {
623 daysToBeRemoved.push(i)
624 }
625 }
626
627 // Remove days from the array that do not have any classes
628 for (i = daysToBeRemoved.length - 1; i >= 0; i--) {
629 calendarItems.splice(daysToBeRemoved[i], 1)
630 }
631 }
632
633 function renderView () {
634 res.render('group-exercise.ejs', {
635 branch: branch,
636 branchName: branchName,
637 calendarBackgrounds: calendarBackgrounds,
638 classDescriptions: classDescriptions,
639 contactInfo: contactInfo,
640 groupExerciseItems: groupExerciseItems,
641 heading: heading,
642 inEnglish: inEnglish,
643 latitude: latitude,
644 location: location,
645 longitude: longitude,
646 navigationData: navigationData,
647 openingTimes: openingTimes,
648 spinningItems: spinningItems,
649 staffMembers: staffMembers,
650 subHeading: subHeading
651 })
652 }
653})
654
655app.get('/tulosta/:typeOfGroupExercise/:branch', function (req, res) {
656 // Check if branch exists before proceeding
657 var bottomBarText = ''
658 var branch = req.params.branch
659 var branchName = ''
660 var calendarBackgrounds = []
661 var groupExerciseCalendarItemsRaw = []
662 var groupExerciseItems = []
663 var spinningCalendarItemsRaw = []
664 var spinningItems = []
665 var typeOfGroupExercise = req.params.typeOfGroupExercise
666
667 checkIfBranchExists(res, branch, fetchBranchInformation)
668
669 function fetchBranchInformation () {
670 connection.query('SELECT nimi FROM branches WHERE nimi_ilman_skandeja = "' + branch + '"', function (error, results, fields) {
671 if (error) throw error
672 branchName = results[0].nimi
673 fetchGroupExerciseCalendarBackgrounds()
674 })
675 }
676
677 function fetchGroupExerciseCalendarBackgrounds () {
678 connection.query('SELECT kuva, tyyppi FROM group_exercise_calendar_backgrounds WHERE toimipiste = "' + branch + '"', function (error, results, fields) {
679 if (error) throw error
680 for (var i = 0; i < results.length; i++) {
681 if (typeof results[i] !== 'undefined' && results[i].tyyppi === 'ryhmaliikunta') {
682 calendarBackgrounds.ryhmaliikunta = results[i].kuva
683 }
684 if (typeof results[i] !== 'undefined' && results[i].tyyppi === 'spinning') {
685 calendarBackgrounds.spinning = results[i].kuva
686 }
687 }
688 checkTypeOfGroupExercise()
689 })
690 }
691
692 function checkTypeOfGroupExercise () {
693 if (typeOfGroupExercise === 'ryhmaliikunta') {
694 fetchGroupExerciseCalendarItems()
695 } else if (typeOfGroupExercise === 'spinning') {
696 fetchSpinningCalendarItems()
697 }
698 }
699
700 function fetchGroupExerciseCalendarItems () {
701 connection.query('SELECT paiva, tunnin_aika_nimi_ja_ohjaaja FROM group_exercise_calendar WHERE toimipiste = "' + branch + '" AND tyyppi = "ryhmaliikunta"', function (error, results, fields) {
702 if (error) throw error
703 groupExerciseCalendarItemsRaw = results
704 organizeCalendarItems(groupExerciseCalendarItemsRaw, groupExerciseItems)
705 })
706 }
707
708 function fetchSpinningCalendarItems () {
709 connection.query('SELECT paiva, tunnin_aika_nimi_ja_ohjaaja FROM group_exercise_calendar WHERE toimipiste = "' + branch + '" AND tyyppi = "spinning"', function (error, results, fields) {
710 if (error) throw error
711 spinningCalendarItemsRaw = results
712 organizeCalendarItems(spinningCalendarItemsRaw, spinningItems)
713 })
714 }
715
716 function organizeCalendarItems (calendarItemsRaw, calendarItems) {
717 var daysOfTheWeek = ['maanantai', 'tiistai', 'keskiviikko', 'torstai', 'perjantai', 'lauantai', 'sunnuntai']
718 var daysOfTheWeekLANG = ['Maanantai', 'Tiistai', 'Keskiviikko', 'Torstai', 'Perjantai', 'Lauantai', 'Sunnuntai']
719
720 // Create arrays to hold items for each day and give each day a heading
721 for (var i = 0; i < daysOfTheWeekLANG.length; i++) {
722 calendarItems.push(new Array(daysOfTheWeekLANG[i]))
723 }
724
725 // Populate the arrays with classes for each day
726 for (i = 0; i < calendarItemsRaw.length; i++) {
727 for (var ii = 0; ii < daysOfTheWeek.length; ii++) {
728 if (calendarItemsRaw[i].paiva === daysOfTheWeek[ii]) {
729 calendarItems[ii].push(calendarItemsRaw[i].tunnin_aika_nimi_ja_ohjaaja)
730 }
731 }
732 }
733
734 // Check which days do not have classes
735 var daysToBeRemoved = []
736 for (i = 0; i < calendarItems.length; i++) {
737 if (calendarItems[i].length === 1) {
738 daysToBeRemoved.push(i)
739 }
740 }
741
742 // Remove days from the array that do not have any classes
743 for (i = daysToBeRemoved.length - 1; i >= 0; i--) {
744 calendarItems.splice(daysToBeRemoved[i], 1)
745 }
746 fetchSpinningCalendarBottomBarText()
747 }
748
749 function fetchSpinningCalendarBottomBarText () {
750 connection.query('SELECT alapalkin_teksti FROM group_exercise_calendar_print WHERE toimipiste = "' + branch + '" AND tyyppi = "' + typeOfGroupExercise + '"', function (error, results, fields) {
751 if (error) throw error
752 bottomBarText = results
753 renderView()
754 })
755 }
756
757 function renderView () {
758 res.render('group-exercise-print.ejs', {
759 bottomBarText: bottomBarText,
760 branchName: branchName,
761 calendarBackgrounds: calendarBackgrounds,
762 groupExerciseItems: groupExerciseItems,
763 spinningItems: spinningItems
764 })
765 }
766})
767
768/*****************************/
769/* Content management routes */
770/*****************************/
771
772app.get('/kirjaudu', function (req, res) {
773 res.render('login.ejs', {
774 username: ''
775 })
776})
777
778app.post('/kirjaudu', function (req, res) {
779 var username = req.body.username || ''
780 var password = req.body.password || ''
781
782 if ((username === 'Ryhmäliikunta' && password === 'g2VcKTNfxA3z') || (username === 'Ylläpitäjä' && password === 'E9KB3mNsDX72')) {
783 req.session.loggedIn = true
784 req.session.username = username
785 res.redirect('yllapito')
786 } else {
787 res.render('login.ejs', {
788 username: username
789 })
790 }
791})
792
793app.get('/kirjaudu-ulos', function (req, res) {
794 req.session.loggedIn = false
795 req.session.username = ''
796 res.redirect('/kirjaudu')
797})
798
799app.get('/yllapito', function (req, res) {
800 var data = []
801 var namesOfAllBranches = []
802 var tableNames = []
803 var username = req.session.username
804 if (req.session.loggedIn === true) {
805 fetchNamesOfEachBranch()
806 } else {
807 res.redirect('kirjaudu')
808 }
809
810 function fetchNamesOfEachBranch () {
811 connection.query('SELECT nimi_ilman_skandeja FROM branches', function (error, results, fields) {
812 if (error) throw error
813 namesOfAllBranches = results
814 fetchTableNames()
815 })
816 }
817
818 function fetchTableNames () {
819 connection.query('SELECT table_name FROM information_schema.tables WHERE table_schema = "kuntokes_energy"', function (error, results, fields) {
820 if (error) throw error
821 tableNames = results
822 fetchDataFromTable(tableNames[0].table_name, 0)
823 })
824 }
825
826 // Iterate using a recursive function because a for loop does not work with the asynchronous 'connection.query' function
827 function fetchDataFromTable (tableName, i) {
828 if (i < tableNames.length - 1) {
829 connection.query('SELECT * FROM ' + tableName, function (error, results, fields) {
830 if (error) throw error
831 data.push(results)
832 i++
833 fetchDataFromTable(tableNames[i].table_name, i)
834 })
835 } else {
836 connection.query('SELECT * FROM ' + tableName, function (error, results, fields) {
837 if (error) throw error
838 data.push(results)
839 renderView()
840 })
841 }
842 }
843
844 function renderView () {
845 res.render('manage-content.ejs', {
846 data: data,
847 namesOfAllBranches: namesOfAllBranches,
848 username: username
849 })
850 }
851})
852
853app.post('/update/:table', function (req, res) {
854 var queryParameters = req.query
855 var table = mysql.escape(req.params.table).slice(1, -1)
856 var SQLQuery = 'UPDATE ' + table + ' SET '
857
858 if (req.session.loggedIn === true) {
859 checkIfTableExists()
860 } else {
861 res.redirect('kirjaudu')
862 }
863
864 function checkIfTableExists () {
865 connection.query('SELECT id FROM ' + table + ' LIMIT 1', function (error, results, fields) {
866 if (!error) {
867 updateRecord()
868 } else {
869 console.log('Cannot update the record because table ' + table + ' was not found.')
870 }
871 })
872 }
873
874 function updateRecord () {
875 // Get the name of the last property in the queryParameters object
876 var lastProperty
877 for (lastProperty in queryParameters);
878 // Form the SQL query string
879 for (var key in queryParameters) {
880 if (key === 'id') {
881 // Do nothing if id
882 } else if (key === lastProperty) {
883 // Omit the last comma for the last property
884 SQLQuery += key + '=' + mysql.escape(queryParameters[key]) + ' '
885 } else {
886 SQLQuery += key + '=' + mysql.escape(queryParameters[key]) + ', '
887 }
888 }
889 SQLQuery += 'WHERE id=' + mysql.escape(queryParameters.id)
890 performDatabaseQuery()
891 }
892 function performDatabaseQuery () {
893 connection.query(SQLQuery, function (error, results, fields) {
894 if (error) throw error
895 res.redirect('/yllapito')
896 })
897 }
898})
899
900app.post('/insert/:table', function (req, res) {
901 var queryParameters = req.query
902 var table = mysql.escape(req.params.table).slice(1, -1)
903 var SQLQuery = 'INSERT INTO ' + table + ' ('
904
905 if (req.session.loggedIn === true) {
906 checkIfTableExists()
907 } else {
908 res.redirect('kirjaudu')
909 }
910
911 function checkIfTableExists () {
912 connection.query('SELECT id FROM ' + table + ' LIMIT 1', function (error, results, fields) {
913 if (!error) {
914 insertRecord()
915 } else {
916 console.log('Cannot update the record because table was not found.')
917 }
918 })
919 }
920
921 function insertRecord () {
922 // Get the name of the last property in the queryParameters object
923 var lastProperty
924 for (lastProperty in queryParameters);
925 // Form the SQL query string
926 for (var key in queryParameters) {
927 if (key === 'id') {
928 // Do nothing if id
929 } else if (key === lastProperty) {
930 // Add closing parenthesis for the last property
931 SQLQuery += '' + key + ') VALUES ('
932 } else {
933 SQLQuery += '' + key + ', '
934 }
935 }
936 for (key in queryParameters) {
937 if (key === 'id') {
938 // Do nothing if id
939 } else if (key === lastProperty) {
940 // Add closing parenthesis for the last property
941 SQLQuery += mysql.escape(queryParameters[key]) + ')'
942 } else {
943 SQLQuery += mysql.escape(queryParameters[key]) + ', '
944 }
945 }
946 performDatabaseQuery()
947 }
948 function performDatabaseQuery () {
949 connection.query(SQLQuery, function (error, results, fields) {
950 if (error) throw error
951 res.redirect('/yllapito')
952 })
953 }
954})
955
956app.post('/insert-branch/:table', function (req, res) {
957 var queryParameters = req.query
958 var table = mysql.escape(req.params.table).slice(1, -1)
959 var SQLQuery = 'INSERT INTO ' + table + ' ('
960 if (req.session.loggedIn === true) {
961 checkIfTableExists()
962 } else {
963 res.redirect('kirjaudu')
964 }
965
966 function checkIfTableExists () {
967 connection.query('SELECT id FROM ' + table + ' LIMIT 1', function (error, results, fields) {
968 if (!error) {
969 insertRecord()
970 } else {
971 console.log('Cannot update the record because table was not found.')
972 }
973 })
974 }
975
976 function insertRecord () {
977 // Get the name of the last property in the queryParameters object
978 var lastProperty
979 for (lastProperty in queryParameters);
980 // Form the SQL query string
981 for (var key in queryParameters) {
982 if (key === 'id') {
983 // Do nothing if id
984 } else if (key === lastProperty) {
985 // Add closing parenthesis for the last property
986 SQLQuery += '' + key + ') VALUES ('
987 } else {
988 SQLQuery += '' + key + ', '
989 }
990 }
991 for (key in queryParameters) {
992 if (key === 'id') {
993 // Do nothing if id
994 } else if (key === lastProperty) {
995 // Add closing parenthesis for the last property
996 SQLQuery += mysql.escape(queryParameters[key]) + ')'
997 } else {
998 SQLQuery += mysql.escape(queryParameters[key]) + ', '
999 }
1000 }
1001 insertColumnsToGroupExerciseClassesTable()
1002 }
1003
1004 function insertColumnsToGroupExerciseClassesTable () {
1005 connection.query('ALTER TABLE group_exercise_classes ADD COLUMN ' + queryParameters.nimi_ilman_skandeja + ' VARCHAR(45) NULL', function (error, results, fields) {
1006 if (error) throw error
1007 insertColumnsToGymServicesTable()
1008 })
1009 }
1010
1011 function insertColumnsToGymServicesTable () {
1012 connection.query('ALTER TABLE gym_services ADD COLUMN ' + queryParameters.nimi_ilman_skandeja + ' VARCHAR(45) NULL', function (error, results, fields) {
1013 if (error) throw error
1014 insertColumnsToMassageServicesTable()
1015 })
1016 }
1017
1018 function insertColumnsToMassageServicesTable () {
1019 connection.query('ALTER TABLE massage_services ADD COLUMN ' + queryParameters.nimi_ilman_skandeja + ' VARCHAR(45) NULL', function (error, results, fields) {
1020 if (error) throw error
1021 insertColumnsToPhysiotherapyServicesTable()
1022 })
1023 }
1024
1025 function insertColumnsToPhysiotherapyServicesTable () {
1026 connection.query('ALTER TABLE physiotherapy_services ADD COLUMN ' + queryParameters.nimi_ilman_skandeja + ' VARCHAR(45) NULL', function (error, results, fields) {
1027 if (error) throw error
1028 insertColumnsToStaffTable()
1029 })
1030 }
1031
1032 function insertColumnsToStaffTable () {
1033 connection.query('ALTER TABLE staff ADD COLUMN ' + queryParameters.nimi_ilman_skandeja + ' VARCHAR(45) NULL', function (error, results, fields) {
1034 if (error) throw error
1035 performDatabaseQuery()
1036 })
1037 }
1038
1039 function performDatabaseQuery () {
1040 connection.query(SQLQuery, function (error, results, fields) {
1041 if (error) throw error
1042 res.redirect('/yllapito')
1043 })
1044 }
1045})
1046
1047app.post('/delete/:table', function (req, res) {
1048 var queryParameters = req.query
1049 var table = mysql.escape(req.params.table).slice(1, -1)
1050 var SQLQuery = 'DELETE FROM ' + table + ' WHERE id=' + mysql.escape(queryParameters.id)
1051
1052 if (req.session.loggedIn === true) {
1053 checkIfTableExists()
1054 } else {
1055 res.redirect('kirjaudu')
1056 }
1057
1058 function checkIfTableExists () {
1059 connection.query('SELECT id FROM ' + table + ' LIMIT 1', function (error, results, fields) {
1060 if (!error) {
1061 performDatabaseQuery()
1062 } else {
1063 console.log('Cannot update the record because table was not found.')
1064 }
1065 })
1066 }
1067
1068 function performDatabaseQuery () {
1069 connection.query(SQLQuery, function (error, results, fields) {
1070 if (error) throw error
1071 res.redirect('/yllapito')
1072 })
1073 }
1074})
1075
1076app.post('/delete-branch/:table', function (req, res) {
1077 var queryParameters = req.query
1078 var table = mysql.escape(req.params.table).slice(1, -1)
1079 var SQLQuery = 'DELETE FROM ' + table + ' WHERE id=' + mysql.escape(queryParameters.id)
1080
1081 if (req.session.loggedIn === true) {
1082 checkIfTableExists()
1083 } else {
1084 res.redirect('kirjaudu')
1085 }
1086
1087 function checkIfTableExists () {
1088 connection.query('SELECT id FROM ' + table + ' LIMIT 1', function (error, results, fields) {
1089 if (!error) {
1090 performDatabaseQuery()
1091 } else {
1092 console.log('Cannot update the record because table was not found.')
1093 }
1094 })
1095 }
1096
1097 function performDatabaseQuery () {
1098 connection.query(SQLQuery, function (error, results, fields) {
1099 if (error) throw error
1100 deleteGroupExerciseClassesTableColumn()
1101 })
1102 }
1103
1104 function deleteGroupExerciseClassesTableColumn () {
1105 connection.query('ALTER TABLE group_exercise_classes DROP COLUMN ' + queryParameters.branch, function (error, results, fields) {
1106 if (error) throw error
1107 deleteGymServicesTableColumn()
1108 })
1109 }
1110
1111 function deleteGymServicesTableColumn () {
1112 connection.query('ALTER TABLE gym_services DROP COLUMN ' + queryParameters.branch, function (error, results, fields) {
1113 if (error) throw error
1114 deleteMassageServicesTableColumn()
1115 })
1116 }
1117
1118 function deleteMassageServicesTableColumn () {
1119 connection.query('ALTER TABLE massage_services DROP COLUMN ' + queryParameters.branch, function (error, results, fields) {
1120 if (error) throw error
1121 deletePhysiotherapyServicesTableColumn()
1122 })
1123 }
1124
1125 function deletePhysiotherapyServicesTableColumn () {
1126 connection.query('ALTER TABLE physiotherapy_services DROP COLUMN ' + queryParameters.branch, function (error, results, fields) {
1127 if (error) throw error
1128 deleteStaffTableColumn()
1129 })
1130 }
1131
1132 function deleteStaffTableColumn () {
1133 connection.query('ALTER TABLE staff DROP COLUMN ' + queryParameters.branch, function (error, results, fields) {
1134 if (error) throw error
1135 res.redirect('/yllapito')
1136 })
1137 }
1138})
1139
1140app.post('/upload', function (req, res) {
1141 if (req.session.loggedIn === true) {
1142 if (!req.files) return res.status(400).send('No files were uploaded.')
1143 var uploadedFile = req.files.image
1144 var uploadPath = req.query.uploadpath
1145 // Move the file to the correct directory
1146 uploadedFile.mv(__dirname + '/public/img/' + uploadPath + uploadedFile.name, function (err) {
1147 if (err) {
1148 return res.status(500).send(err)
1149 }
1150 res.send('File uploaded!')
1151 })
1152 } else {
1153 res.redirect('kirjaudu')
1154 }
1155})
1156
1157// Error pages
1158
1159app.get('*', function (req, res) {
1160 res.status(404).render('404.ejs')
1161})
1162
1163// Server
1164app.listen(8000, function () {
1165 console.log('Server started on http://localhost:8000/')
1166})