1 import { DatePipe } from '@angular/common';
2 import { Component, ElementRef, HostListener, OnInit, ViewChild } from '@angular/core';
3 import { FormBuilder, FormGroup, Validators, FormArray, ValidatorFn, AbstractControl } from '@angular/forms';
4 import { ActivatedRoute, Router } from '@angular/router';
5 import { ToastrService } from 'ngx-toastr';
6 import { Subscription } from 'rxjs';
7 import { first } from 'rxjs/operators';
8 import { environment } from 'src/environments/environment';
9 import { HttpCommunicationService } from '../reusable/httpCommunicationService/http-communication.service';
10 import { User } from '../user';
11
12 @Component({
13 selector: 'app-editar-repte',
14 templateUrl: './editar-repte.component.html',
15 styleUrls: ['./editar-repte.component.css']
16 })
17 export class EditarRepteComponent implements OnInit {
18
19
20 constructor(private router: Router, private aRouter: ActivatedRoute, private fb: FormBuilder, private httpClient: HttpCommunicationService,
21 public datepipe: DatePipe, public toastr: ToastrService) { }
22
23 hasUnsavedData(): boolean {
24 if (this.formDone) {
25 return false;
26 } else {
27 return this.repteForm.dirty;
28 }
29 }
30
31 currentUser: User;
32
33 public fileStorageUrl = environment.api + '/image/';
34
35 repteForm: FormGroup;
36 radioValue = 'equip';
37 radioToSValue = 'hubandrock';
38 currentTab: number = 0; // Current tab is set to be the first tab (0)
39 numberOfTabs = 3; //0 + 1 = 2 tabs
40
41 fotosReptePreview: any = {};
42 fotosRepte: any = {};
43
44 objectFotosPreview: any = {};
45 objectFotos: any = {};
46
47 objectSolucionsPreview: any = {};
48 objectSolucions: any = {};
49
50 objectPartnersPreview: any = {};
51 objectPartners: any = {};
52
53 objectJuratsPreview: any = {};
54 objectJurats: any = {};
55
56 repte;
57 idRepte;
58
59 success = false;
60
61 eliminat = false;
62 enviat = false;
63
64 formDone = false;
65
66 checkUntouched = false;
67
68 pdfArray = [];
69 pdfChanged = false;
70
71 subscriptionForm$: Subscription;
72 subscriptionHttp1$: Subscription;
73
74 @ViewChild('inputFile') myInputVariable: ElementRef;
75
76
77 validationMessages = {
78 'nomRepte': {
79 'required': 'És un camp requerit',
80 'maxlength': 'Nom massa llarg',
81 'minlength': 'Nom massa curt'
82 },
83 'descripcioBreuRepte': {
84 'required': 'És un camp requerit',
85 'maxlength': 'Descripció massa llarga',
86 'minlength': 'Descripció massa curta'
87 },
88 'descripcioDetalladaRepte': {
89 'required': 'És un camp requerit',
90 'maxlength': 'Descripció massa llarga',
91 'minlength': 'Descripció massa curta'
92 },
93 'fotoPortada': {
94 'required': 'És un camp requerit',
95 },
96 'videoSolucio': {
97 'pattern': 'No és un enllaç de Youtube vàlid',
98
99 },
100 'checkboxGroup': {
101 'requireCheckboxesToBeChecked': 'Selecciona almenys una categoria!'
102 },
103 'datesGroup': {
104 'dataIniciBiggerThanFinal': 'El repte no pot acabar abans de començar!'
105 },
106 'limitParticipants': {
107 'pattern': 'Entra un nombre de participants vàlid',
108 },
109 'dataInici': {
110 'required': 'És un camp requerit',
111 'dateShorterThanToday': 'La data no pot ser inferior a avui'
112 },
113 'dataFinalitzacio': {
114 'required': 'És un camp requerit',
115 'dateShorterThanToday': 'La data no pot ser inferior a avui'
116 },
117 'nomPremi': {
118 'required': 'És un camp requerit',
119 'maxlength': 'Nom massa llarg',
120 'minlength': 'Nom massa curt'
121 },
122 'dotacioPremi': {
123 'required': 'És un camp requerit',
124 'minlength': 'Premi invàlid'
125 },
126 'descripcioPremi': {
127 'required': 'És un camp requerit',
128 'maxlength': 'Descripció massa llarga',
129 'minlength': 'Descripció massa curta'
130 },
131 'fotoPremi': {
132
133 },
134 'nomSolucio': {
135 'required': 'És un camp requerit',
136 'maxlength': 'Nom massa llarg',
137 'minlength': 'Nom massa curt'
138 },
139 'descripcioSolucio': {
140 'required': 'És un camp requerit',
141 'maxlength': 'Descripció massa llarga',
142 'minlength': 'Descripció massa curta'
143 },
144 'fotoSolucio': {
145 'required': 'És un camp requerit',
146 },
147 'nomPartner': {
148 'maxlength': 'Nom massa llarg', //Falta fer que sigui required if tal.
149 'minlength': 'Nom massa curt'
150 },
151 'breuDescripcioPartner': {
152 'maxlength': 'Descripció massa llarga',
153 'minlength': 'Descripció massa curta'
154 },
155 'logoPartner': {
156
157 },
158 'nomCognomsJurat': {
159 'maxlength': 'Nom massa llarg', //Falta fer que sigui required if tal.
160 'minlength': 'Nom massa curt'
161 },
162 'biografiaJurat': {
163 'maxlength': 'Biografia massa llarga',
164 'minlength': 'Biografia massa curta'
165 },
166 'fotoJurat': {
167
168 },
169 'pregunta': {
170 'required': 'És un camp requerit',
171 'maxlength': 'Pregunta massa llarga',
172 'minlength': 'Pregunta invàlida'
173 },
174 'resposta': {
175 'required': 'És un camp requerit.',
176 'maxlength': 'Resposta massa llarga',
177 'minlength': 'Resposta invàlida'
178 },
179 'customTOS': { //Sha de fer required si ha triat customTOS
180 'required': 'És un camp requerit',
181 'maxlength': 'Les bases legals excedeixen el màxim de caràcters',
182 'minlength': 'Bases legals invàlides'
183 },
184
185 'campsErronis': {
186 'errors': 'Hi ha camps erronis, comprova que el formulari estigui omplert correctament'
187 }
188
189 };
190
191
192 formErrors = {
193 'nomRepte': '',
194 'descripcioBreuRepte': '',
195 'descripcioDetalladaRepte': '',
196 'fotoPortada': '',
197 'videoSolucio': '',
198 'checkboxGroup': '',
199 'limitParticipants': '',
200 'datesGroup': '',
201 'dataInici': '',
202 'dataFinalitzacio': '',
203 'nomPremi': '',
204 'dotacioPremi': '',
205 'descripcioPremi': '',
206 'fotoPremi': '',
207 'nomSolucio': '',
208 'descripcioSolucio': '',
209 'fotoSolucio': '',
210 'nomPartner': '',
211 'breuDescripcioPartner': '',
212 'logoPartner': '',
213 'nomCognomsJurat': '',
214 'biografiaJurat': '',
215 'fotoJurat': '',
216 'pregunta': '',
217 'resposta': '',
218 'customTOS': '',
219 'campsErronis': '',
220 };
221
222 ngOnInit(): void {
223 this.idRepte = this.aRouter.snapshot.params.id;
224
225 this.httpClient.currentUser.subscribe(
226 data => {
227 this.currentUser = data;
228 }
229 );
230
231 if (this.idRepte) {
232
233 this.httpClient.getRepte(this.idRepte)
234 .pipe(first())
235 .subscribe(
236 data => {
237 if (data.code == '1') {
238
239 this.repte = data.row;
240
241 let participantsEmpresa = false;
242 let participantsStartups = false;
243 let participantsEstudiants = false;
244 let participantsExperts = false;
245
246 // PATCH PARTICIPANTS
247 for (let index = 0; index < this.repte.participants.length; index++) {
248 const participant = this.repte.participants[index];
249
250 if (participant.participants_name == "Empreses") {
251 // this.repteForm.get('checkboxGroup').patchValue({
252 // empresesCheckbox: [true]
253 // })
254 participantsEmpresa = true;
255 } else if (participant.participants_name == "Startups") {
256 // this.repteForm.get('checkboxGroup').patchValue({
257 // startupsCheckbox: [true]
258 // })
259 participantsStartups = true;
260 } else if (participant.participants_name == "Estudiants") {
261 // this.repteForm.get('checkboxGroup').patchValue({
262 // estudiantsCheckbox: [true]
263 // })
264 participantsEstudiants = true;
265 } else if (participant.participants_name == "Experts") {
266 // this.repteForm.get('checkboxGroup').patchValue({
267 // expertsCheckbox: [true]
268 // })
269 participantsExperts = true;
270 }
271 }
272
273 var regExp = /^.*(youtu.be/|v/|u/w/|embed/|watch?v=|&v=|?v=)([^#&?]*).*/;
274
275 this.repteForm = this.fb.group({
276 nomRepte: ['', [Validators.required, Validators.maxLength(255), Validators.minLength(3)]],
277 descripcioBreuRepte: ['', [Validators.required, Validators.maxLength(280), Validators.minLength(3)]],
278 descripcioDetalladaRepte: ['', [Validators.required, Validators.maxLength(1000), Validators.minLength(3)]],
279 fotoPortada: ['',
280 [Validators.required]
281 ],
282 fotoRepresentativa1: ['', []],
283 fotoRepresentativa2: ['', []],
284 fotoRepresentativa3: ['', []],
285 pdf: [''],
286 videoSolucio: ['', [Validators.pattern(regExp)]], //validador custom youtube format
287 checkboxGroup: this.fb.group({
288 empresesCheckbox: [participantsEmpresa],
289 startupsCheckbox: [participantsStartups],
290 estudiantsCheckbox: [participantsEstudiants],
291 expertsCheckbox: [participantsExperts]
292 }, { validator: requireCheckboxesToBeCheckedValidator() }),
293 limitParticipants: ['', Validators.pattern('[0-9]+')],
294 datesGroup: this.fb.group({
295 dataInici: ['', [Validators.required, dateShorterThanToday]], //Data inici no pot ser anterior a la data actual
296 dataFinalitzacio: ['', [Validators.required, dateShorterThanToday]],
297 }, { validator: dataIniciBiggerThanFinal() }),
298 premiArray: this.fb.array([
299
300 ]),
301 solucioArray: this.fb.array([
302
303 ]),
304 partnerArray: this.fb.array([
305
306 ]),
307 juratArray: this.fb.array([
308
309 ]),
310 preguntaArray: this.fb.array([
311
312 ]),
313
314 customTOS: ['', [Validators.maxLength(5000), Validators.minLength(3)]],
315 });
316
317 this.subscriptionForm$ = this.repteForm.valueChanges.subscribe((data) => {
318 this.logValidationErrors(this.repteForm)
319 });
320
321 this.repteForm.patchValue({
322 nomRepte: this.repte.nom,
323 descripcioBreuRepte: this.repte.descripcio_short,
324 descripcioDetalladaRepte: this.repte.descripcio_long,
325 videoSolucio: this.repte.url_video,
326
327 })
328
329
330 //PATCH INDIVIDUAL EQUIP
331 if (this.repte.individual_equip == 1) {
332 this.radioValue = 'equip'
333 } else if (this.repte.individual_equip == 0) {
334 this.radioValue = 'individual'
335 }
336
337 if (this.repte.limit_participants) {
338 this.repteForm.patchValue({ limitParticipants: this.repte.limit_participants })
339 }
340
341 //PATCH DATES
342 if (this.repte.data_inici) {
343 let dateRepteInici = this.datepipe.transform(this.repte.data_inici, 'yyyy-MM-dd')
344 this.repteForm.get('datesGroup').patchValue({ dataInici: dateRepteInici })
345 }
346
347 if (this.repte.data_final) {
348 let dateRepteFinal = this.datepipe.transform(this.repte.data_final, 'yyyy-MM-dd')
349 this.repteForm.get('datesGroup').patchValue({ dataFinalitzacio: dateRepteFinal })
350 }
351
352 //PATCH RECURSOS
353 if (this.repte.recursos.length) {
354 this.pdfArray = this.repte.recursos
355 console.log(this.pdfArray)
356 }
357
358 //PATCH PREMIS
359 if (this.repte.premis.length) {
360 console.log('length premis', this.repte.premis.length)
361 for (var i = 0; i < this.repte.premis.length; i++) {
362
363 (<FormArray>this.repteForm.get('premiArray')).push(this.addPremiFormGroup());
364
365 (<FormArray>this.repteForm.get('premiArray')).at(i).patchValue({
366 nomPremi: this.repte.premis[i].premi_nom,
367 dotacioPremi: this.repte.premis[i].premi_dotacio,
368 descripcioPremi: this.repte.premis[i].premi_descripcio
369 });
370
371 const fotoPremiName = 'fotoPremi' + i
372
373 this.addPremiToObject(fotoPremiName)
374
375 if (this.repte.premis[i].premi_url_photo) {
376 fetch(this.fileStorageUrl + this.repte.premis[i].premi_url_photo)
377 .then(res => res.blob()) // Gets the response and returns it as a blob
378 .then(blob => {
379 let blobToFile = new File([blob], 'image')
380 this.objectFotos[fotoPremiName] = blobToFile;
381
382 var reader = new FileReader();
383 reader.readAsDataURL(blob)
384 reader.onload = (event: any) => {
385 this.objectFotosPreview[fotoPremiName] = reader.result
386 }
387 })
388 }
389 }
390
391 } else {
392 (<FormArray>this.repteForm.get('premiArray')).push(this.addPremiFormGroup());
393
394 }
395
396 //PATCH SOLUCIONS
397 if (this.repte.solucions.length) {
398 console.log('length solucions', this.repte.solucions.length)
399
400 for (var i = 0; i < this.repte.solucions.length; i++) {
401
402 (<FormArray>this.repteForm.get('solucioArray')).push(this.addSolucioFormGroup());
403
404 (<FormArray>this.repteForm.get('solucioArray')).at(i).patchValue({
405 nomSolucio: this.repte.solucions[i].solucio_nom,
406 descripcioSolucio: this.repte.solucions[i].solucio_descripcio,
407 });
408
409 const fotoSolucioName = 'fotoSolucio' + i
410
411 this.addPremiToObject(fotoSolucioName)
412
413 if (this.repte.solucions[i].solucio_url_photo) {
414 fetch(this.fileStorageUrl + this.repte.solucions[i].solucio_url_photo)
415 .then(res => res.blob()) // Gets the response and returns it as a blob
416 .then(blob => {
417 let blobToFile = new File([blob], 'image')
418 this.objectSolucions[fotoSolucioName] = blobToFile;
419
420 var reader = new FileReader();
421 reader.readAsDataURL(blob)
422 reader.onload = (event: any) => {
423 this.objectSolucionsPreview[fotoSolucioName] = reader.result
424 }
425 })
426 }
427 }
428
429
430 } else {
431 (<FormArray>this.repteForm.get('solucioArray')).push(this.addSolucioFormGroup());
432
433 }
434
435 //PATCH PARTNERS
436 if (this.repte.partners.length) {
437 for (var i = 0; i < this.repte.partners.length; i++) {
438
439 (<FormArray>this.repteForm.get('partnerArray')).push(this.addPartnerFormGroup());
440
441 (<FormArray>this.repteForm.get('partnerArray')).at(i).patchValue({
442 nomPartner: this.repte.partners[i].partner_nom,
443 breuDescripcioPartner: this.repte.partners[i].partner_descripcio,
444 });
445
446 const fotoPartnerName = 'fotoPartner' + i
447
448 this.addPremiToObject(fotoPartnerName)
449
450 if (this.repte.partners[i].partner_url_logo) {
451
452 // (<FormGroup>(<FormGroup>this.repteForm.controls.partnerArray).controls[i]).controls.logoPartner.clearValidators();
453 // (<FormGroup>(<FormGroup>this.repteForm.controls.partnerArray).controls[i]).controls.logoPartner.updateValueAndValidity({ emitEvent: false });
454
455 fetch(this.fileStorageUrl + this.repte.partners[i].partner_url_logo)
456 .then(res => res.blob()) // Gets the response and returns it as a blob
457 .then(blob => {
458 let blobToFile = new File([blob], 'image')
459 this.objectPartners[fotoPartnerName] = blobToFile;
460
461 var reader = new FileReader();
462 reader.readAsDataURL(blob)
463 reader.onload = (event: any) => {
464 this.objectPartnersPreview[fotoPartnerName] = reader.result
465 }
466 this.logValidationErrors()
467
468 })
469 }
470 }
471
472 } else {
473 (<FormArray>this.repteForm.get('partnerArray')).push(this.addPartnerFormGroup());
474
475 }
476
477 //PATCH JURATS
478 if (this.repte.jurats.length) {
479 for (var i = 0; i < this.repte.jurats.length; i++) {
480
481 (<FormArray>this.repteForm.get('juratArray')).push(this.addJuratFormGroup());
482
483 (<FormArray>this.repteForm.get('juratArray')).at(i).patchValue({
484 nomCognomsJurat: this.repte.jurats[i].jurat_nom,
485 biografiaJurat: this.repte.jurats[i].jurat_bio,
486 });
487
488 const fotoJuratName = 'fotoJurat' + i
489
490 this.addPremiToObject(fotoJuratName)
491
492 if (this.repte.jurats[i].jurat_url_photo) {
493
494 // (<FormGroup>(<FormGroup>this.repteForm.controls.juratArray).controls[i]).controls.fotoJurat.clearValidators();
495 // (<FormGroup>(<FormGroup>this.repteForm.controls.juratArray).controls[i]).controls.fotoJurat.updateValueAndValidity({ emitEvent: false });
496
497 fetch(this.fileStorageUrl + this.repte.jurats[i].jurat_url_photo)
498 .then(res => res.blob()) // Gets the response and returns it as a blob
499 .then(blob => {
500 let blobToFile = new File([blob], 'image')
501 this.objectJurats[fotoJuratName] = blobToFile;
502
503 var reader = new FileReader();
504 reader.readAsDataURL(blob)
505 reader.onload = (event: any) => {
506 this.objectJuratsPreview[fotoJuratName] = reader.result
507 }
508 this.logValidationErrors()
509
510 })
511 }
512 }
513
514 } else {
515 (<FormArray>this.repteForm.get('juratArray')).push(this.addJuratFormGroup());
516
517 }
518
519 //PATCH FAQ
520 if (this.repte.faqs.length) {
521 for (var i = 0; i < this.repte.faqs.length; i++) {
522
523 (<FormArray>this.repteForm.get('preguntaArray')).push(this.addPreguntaFormGroup());
524
525 (<FormArray>this.repteForm.get('preguntaArray')).at(i).patchValue({
526 pregunta: this.repte.faqs[i].faq_pregunta,
527 resposta: this.repte.faqs[i].faq_resposta,
528 });
529 }
530
531 } else {
532 (<FormArray>this.repteForm.get('preguntaArray')).push(this.addPreguntaFormGroup());
533
534 }
535 }
536
537 //PATCH CUSTOM TOS
538 if (this.repte.bases_legals == 1) {
539 this.radioToSValue = 'custom'
540 } else if (this.repte.individual_equip == 0) {
541 this.radioToSValue = 'hubandrock'
542 }
543
544 if (this.repte.bases_legals == 1) {
545 this.repteForm.patchValue({ customTOS: this.repte.bases_legals_personals })
546 }
547
548 if (this.radioToSValue == 'hubandrock') {
549
550 this.repteForm.get('customTOS').setValidators([Validators.maxLength(5000), Validators.minLength(3)])
551 this.repteForm.get('customTOS').updateValueAndValidity()
552
553 } else if (this.radioToSValue == 'custom') {
554
555 this.repteForm.get('customTOS').setValidators([Validators.required, Validators.maxLength(5000), Validators.minLength(3)])
556 this.repteForm.get('customTOS').updateValueAndValidity()
557
558 }
559
560 //PATCH FOTOS REPTE
561 if (this.repte.url_photo_main) {
562 fetch(this.fileStorageUrl + this.repte.url_photo_main)
563 .then(res => res.blob()) // Gets the response and returns it as a blob
564 .then(blob => {
565 let blobToFile = new File([blob], 'image')
566 this.fotosRepte.fotoPortada = blobToFile
567
568 var reader = new FileReader();
569 reader.readAsDataURL(blob)
570 reader.onload = (event: any) => {
571 this.fotosReptePreview.fotoPortada = reader.result
572 }
573 this.logValidationErrors()
574 })
575 }
576
577 if (this.repte.url_photo_1) {
578 fetch(this.fileStorageUrl + this.repte.url_photo_1)
579 .then(res => res.blob()) // Gets the response and returns it as a blob
580 .then(blob => {
581 let blobToFile = new File([blob], 'image')
582 this.fotosRepte.fotoRepresentativa1 = blobToFile
583
584 var reader = new FileReader();
585 reader.readAsDataURL(blob)
586 reader.onload = (event: any) => {
587 this.fotosReptePreview.fotoRepresentativa1 = reader.result
588 }
589 this.logValidationErrors()
590
591 })
592 }
593
594 if (this.repte.url_photo_2) {
595 fetch(this.fileStorageUrl + this.repte.url_photo_2)
596 .then(res => res.blob()) // Gets the response and returns it as a blob
597 .then(blob => {
598 let blobToFile = new File([blob], 'image')
599 this.fotosRepte.fotoRepresentativa2 = blobToFile
600
601 var reader = new FileReader();
602 reader.readAsDataURL(blob)
603 reader.onload = (event: any) => {
604 this.fotosReptePreview.fotoRepresentativa2 = reader.result
605 }
606 this.logValidationErrors()
607
608 })
609 }
610
611 if (this.repte.url_photo_3) {
612 fetch(this.fileStorageUrl + this.repte.url_photo_3)
613 .then(res => res.blob()) // Gets the response and returns it as a blob
614 .then(blob => {
615 let blobToFile = new File([blob], 'image')
616 this.fotosRepte.fotoRepresentativa3 = blobToFile
617
618 var reader = new FileReader();
619 reader.readAsDataURL(blob)
620 reader.onload = (event: any) => {
621 this.fotosReptePreview.fotoRepresentativa3 = reader.result
622 }
623 this.logValidationErrors()
624
625 })
626 }
627
628 });
629
630 }
631 }
632
633
634 getInterpolationCondition(name, i) {
635 let stringInterpolation: string = name + i
636 if (name == 'fotoPremi') {
637 if (this.objectFotosPreview[stringInterpolation]) {
638 return true;
639 } else {
640 return false;
641 }
642 }
643 else if (name == 'fotoSolucio') {
644 if (this.objectSolucionsPreview[stringInterpolation]) {
645 return true;
646 } else {
647 return false;
648 }
649 }
650 else if (name == 'fotoPartner') {
651 if (this.objectPartnersPreview[stringInterpolation]) {
652 return true;
653 } else {
654 return false;
655 }
656 }
657 else if (name == 'fotoJurat') {
658 if (this.objectJuratsPreview[stringInterpolation]) {
659 return true;
660 } else {
661 return false;
662 }
663 }
664
665 }
666
667 getObjectProperty(name, i) {
668 let stringInterpolation: string = name + i
669 if (name == 'fotoPremi') {
670 return this.objectFotosPreview[stringInterpolation];
671 }
672 else if (name == 'fotoSolucio') {
673 return this.objectSolucionsPreview[stringInterpolation];
674 }
675 else if (name == 'fotoPartner') {
676 return this.objectPartnersPreview[stringInterpolation];
677 }
678 else if (name == 'fotoJurat') {
679 return this.objectJuratsPreview[stringInterpolation];
680 }
681
682 }
683
684
685 logValidationErrors(group: FormGroup = this.repteForm): void {
686 console.log('LOG VALIDATION CRIDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAT')
687 Object.keys(group.controls).forEach((key: string) => {
688 const abstractControl = group.get(key);
689
690 this.formErrors[key] = '';
691 console.log('hi puto hi ha foto portada o no?', this.fotosRepte.fotoPortada)
692
693 if (!this.fotosRepte.fotoPortada) {
694 this.repteForm.get('fotoPortada').setValidators([Validators.required])
695 this.repteForm.get('fotoPortada').updateValueAndValidity({ emitEvent: false })
696 } else {
697 this.repteForm.get('fotoPortada').clearValidators()
698 this.repteForm.get('fotoPortada').updateValueAndValidity({ emitEvent: false })
699 }
700
701 if (abstractControl && !abstractControl.valid &&
702 (abstractControl.touched || abstractControl.dirty)) {
703 const messages = this.validationMessages[key];
704
705 for (const errorKey in abstractControl.errors) {
706 if (errorKey) {
707 this.formErrors[key] += messages[errorKey] + ' ';
708 }
709 }
710 }
711
712 if (abstractControl instanceof FormGroup) {
713 this.logValidationErrors(abstractControl);
714 }
715
716 if (abstractControl instanceof FormArray) {
717
718 if (abstractControl == this.repteForm.get('partnerArray')) {
719
720 let partnerArrayCounter = 0;
721
722 for (let control of (<FormArray>this.repteForm.get('partnerArray')).controls) {
723 if (control instanceof FormGroup) {
724 console.log('LOGO JURAT VALUE', this.objectPartners)
725 console.log('AKFJÑLASJDFÑLKAJSDFÑASJFÑALDSJFÑLAJSD JODER', this.objectPartners['fotoPartner' + partnerArrayCounter])
726
727 if (control.controls.nomPartner.value ||
728 control.controls.breuDescripcioPartner.value ||
729 this.objectPartners['fotoPartner' + partnerArrayCounter]) {
730 control.controls.nomPartner.setValidators([Validators.required, Validators.maxLength(255), Validators.minLength(3)])
731 control.controls.nomPartner.updateValueAndValidity({ emitEvent: false })
732
733
734 control.controls.breuDescripcioPartner.setValidators([Validators.required, Validators.maxLength(900), Validators.minLength(3)])
735 control.controls.breuDescripcioPartner.updateValueAndValidity({ emitEvent: false })
736
737 if (!this.objectPartners['fotoPartner' + partnerArrayCounter]) {
738 control.controls.logoPartner.setValidators([Validators.required])
739 control.controls.logoPartner.updateValueAndValidity({ emitEvent: false })
740 } else {
741 control.controls.logoPartner.clearValidators()
742 control.controls.logoPartner.updateValueAndValidity({ emitEvent: false })
743 }
744
745 control.updateValueAndValidity({ emitEvent: false });
746 }
747 else {
748
749 control.controls.nomPartner.setValidators([Validators.maxLength(255), Validators.minLength(3)])
750 control.controls.nomPartner.updateValueAndValidity({ emitEvent: false })
751
752
753 control.controls.breuDescripcioPartner.setValidators([Validators.maxLength(900), Validators.minLength(3)])
754 control.controls.breuDescripcioPartner.updateValueAndValidity({ emitEvent: false })
755
756
757 control.controls.logoPartner.clearValidators()
758 control.controls.logoPartner.updateValueAndValidity({ emitEvent: false })
759
760 control.updateValueAndValidity({ emitEvent: false });
761
762 }
763 }
764 partnerArrayCounter++;
765 }
766
767 } else if (abstractControl == this.repteForm.get('juratArray')) {
768
769 let juratArrayCounter = 0;
770
771 for (let control of (<FormArray>this.repteForm.get('juratArray')).controls) {
772 if (control instanceof FormGroup) {
773
774 if (control.controls.nomCognomsJurat.value ||
775 control.controls.biografiaJurat.value ||
776 this.objectJurats['fotoJurat' + juratArrayCounter]) {
777
778 control.controls.nomCognomsJurat.setValidators([Validators.required, Validators.maxLength(255), Validators.minLength(3)])
779 control.controls.nomCognomsJurat.updateValueAndValidity({ emitEvent: false })
780
781
782 control.controls.biografiaJurat.setValidators([Validators.required, Validators.maxLength(900), Validators.minLength(3)])
783 control.controls.biografiaJurat.updateValueAndValidity({ emitEvent: false })
784
785 if (!this.objectJurats['fotoJurat' + juratArrayCounter]) {
786 control.controls.fotoJurat.setValidators([Validators.required])
787 control.controls.fotoJurat.updateValueAndValidity({ emitEvent: false })
788 } else {
789 control.controls.fotoJurat.clearValidators()
790 control.controls.fotoJurat.updateValueAndValidity({ emitEvent: false })
791 }
792
793 control.updateValueAndValidity({ emitEvent: false });
794
795 } else {
796
797 control.controls.nomCognomsJurat.setValidators([Validators.maxLength(255), Validators.minLength(3)])
798 control.controls.nomCognomsJurat.updateValueAndValidity({ emitEvent: false })
799
800
801 control.controls.biografiaJurat.setValidators([Validators.maxLength(900), Validators.minLength(3)])
802 control.controls.biografiaJurat.updateValueAndValidity({ emitEvent: false })
803
804
805 control.controls.fotoJurat.clearValidators()
806 control.controls.fotoJurat.updateValueAndValidity({ emitEvent: false })
807
808 control.updateValueAndValidity({ emitEvent: false });
809
810 }
811 }
812 juratArrayCounter++;
813 }
814 }
815 }
816
817 })
818
819 }
820
821 todayDate() {
822 let today = new Date();
823 today.setDate(today.getDate() + 1)
824 let todayFormat = this.datepipe.transform(today, 'yyyy-MM-dd');
825
826 return todayFormat;
827 }
828
829 tomorrowDate() {
830 let tomorrow = new Date();
831 tomorrow.setDate(tomorrow.getDate() + 2);
832 let tomorrowFormat = this.datepipe.transform(tomorrow, 'yyyy-MM-dd');
833
834 return tomorrowFormat;
835 }
836
837 nextPrev(n) {
838 this.currentTab = this.currentTab + n;
839 }
840
841 nextPrevBottom(n) {
842 this.currentTab = this.currentTab + n;
843 window.scrollTo(0, 0)
844 }
845
846 changeRadio(value) {
847 this.radioValue = value;
848
849 }
850
851 changeRadioToS(value) {
852 this.radioToSValue = value;
853
854 if (this.radioToSValue == 'hubandrock') {
855
856 this.repteForm.get('customTOS').setValidators([Validators.maxLength(5000), Validators.minLength(3)])
857 this.repteForm.get('customTOS').updateValueAndValidity()
858
859 } else if (this.radioToSValue == 'custom') {
860
861 this.repteForm.get('customTOS').setValidators([Validators.required, Validators.maxLength(5000), Validators.minLength(3)])
862 this.repteForm.get('customTOS').updateValueAndValidity()
863
864 }
865 }
866
867 onPdfSelected(event) {
868 if (event.target.files) {
869 let pdfCleared = false;
870
871 for (let index = 0; index < event.target.files.length; index++) {
872 const element = event.target.files[index];
873
874 if (element.size < 1000000) {
875 if (!pdfCleared) {
876 this.pdfArray = []
877 pdfCleared = true;
878 }
879
880 this.pdfArray.push(element);
881 this.pdfChanged = true;
882 } else {
883 alert('L'arxiu supera el límit de 1MB')
884 }
885 }
886 }
887 console.log(this.pdfArray)
888 }
889
890 resetPdfArray() {
891 this.pdfArray = [];
892 }
893
894 onFileRepteFoto(event) {
895 if (event.target.files) {
896 if (event.target.files[0].size < 1000000) {
897 const inputName = event.target.name;
898
899 this.fotosRepte[inputName] = event.target.files[0]
900
901 console.log(this.fotosRepte)
902
903 var reader = new FileReader();
904 reader.readAsDataURL(event.target.files[0])
905 reader.onload = (event: any) => {
906 this.fotosReptePreview[inputName] = reader.result
907 console.log(this.fotosReptePreview)
908 }
909 } else {
910 alert('L'arxiu supera el límit de 1MB')
911 }
912 }
913 }
914
915 onFileSelected(event, index?) {
916 if (event.target.files) {
917 if (event.target.files[0].size < 1000000) {
918 console.log('fiel pujat', event.target.files[0])
919 let inputName = event.target.name;
920 this.objectFotos[inputName] = event.target.files[0]
921
922 console.log(inputName, index)
923
924 var reader = new FileReader();
925 reader.readAsDataURL(event.target.files[0])
926 reader.onload = (event: any) => {
927 this.objectFotosPreview[inputName] = reader.result
928 }
929 } else {
930 alert('L'arxiu supera el límit de 1MB')
931 }
932 }
933
934 }
935
936 onFileSelectedSolucio(event, index?) {
937 if (event.target.files) {
938 if (event.target.files[0].size < 1000000) {
939 console.log('fiel pujat', event.target.files[0])
940 let inputName = event.target.name;
941 this.objectSolucions[inputName] = event.target.files[0]
942
943 console.log(inputName, index)
944
945 var reader = new FileReader();
946 reader.readAsDataURL(event.target.files[0])
947 reader.onload = (event: any) => {
948 this.objectSolucionsPreview[inputName] = reader.result
949 }
950 } else {
951 alert('L'arxiu supera el límit de 1MB')
952 }
953
954 }
955 console.log(this.objectSolucionsPreview)
956 }
957
958 onFileSelectedPartner(event, index?) {
959 if (event.target.files) {
960 if (event.target.files[0].size < 1000000) {
961 console.log('file PARTNER pujat', event.target.files[0])
962 let inputName = event.target.name;
963 this.objectPartners[inputName] = event.target.files[0]
964
965 console.log(inputName, index)
966
967 var reader = new FileReader();
968 reader.readAsDataURL(event.target.files[0])
969 reader.onload = (event: any) => {
970 this.objectPartnersPreview[inputName] = reader.result
971 }
972 this.logValidationErrors()
973
974 } else {
975 alert('L'arxiu supera el límit de 1MB')
976 }
977
978 }
979 console.log(this.objectPartnersPreview)
980 }
981
982 onFileSelectedJurat(event, index?) {
983 if (event.target.files) {
984 if (event.target.files[0].size < 1000000) {
985 console.log('fiel pujat', event.target.files[0])
986 let inputName = event.target.name;
987 this.objectJurats[inputName] = event.target.files[0]
988
989 console.log(inputName, index)
990
991 var reader = new FileReader();
992 reader.readAsDataURL(event.target.files[0])
993 reader.onload = (event: any) => {
994 this.objectJuratsPreview[inputName] = reader.result
995 }
996 this.logValidationErrors()
997
998 } else {
999 alert('L'arxiu supera el límit de 1MB')
1000 }
1001
1002 }
1003 console.log(this.objectJuratsPreview)
1004 }
1005
1006
1007 eliminarFoto(fotoName) {
1008 console.log("INSIDEEEEEEEEEEEEEEEEEE TOOOOOOOOOOOOOO DEEEEEEEEEEEPPPPPPPPPP", fotoName)
1009 let str = fotoName;
1010 let arraySplit = str.split(/([0-9]+)/) //fotoPremi
1011
1012 if (arraySplit[0] == 'fotoPremi') {
1013 let confirmWindow = confirm('Estàs segur que vol eliminar aquesta foto?')
1014
1015 if (confirmWindow == true) {
1016 this.objectFotosPreview[fotoName] = '';
1017 this.objectFotos[fotoName] = '';
1018 }
1019 }
1020 else if (arraySplit[0] == 'fotoSolucio') {
1021 let confirmWindow = confirm('Estàs segur que vol eliminar aquesta foto?')
1022
1023 if (confirmWindow == true) {
1024 this.objectSolucionsPreview[fotoName] = '';
1025 this.objectSolucions[fotoName] = '';
1026 }
1027 }
1028 else if (arraySplit[0] == 'fotoPartner') {
1029 (<FormArray>this.repteForm.get('partnerArray')).at(arraySplit[1]).patchValue({
1030 logoPartner: null
1031 })
1032
1033 let confirmWindow = confirm('Estàs segur que vol eliminar aquesta foto?')
1034
1035 if (confirmWindow == true) {
1036 this.objectPartnersPreview[fotoName] = '';
1037 this.objectPartners[fotoName] = '';
1038 this.logValidationErrors()
1039 }
1040 }
1041 else if (arraySplit[0] == 'fotoJurat') {
1042
1043 (<FormArray>this.repteForm.get('juratArray')).at(arraySplit[1]).patchValue({
1044 fotoJurat: null
1045 })
1046
1047 let confirmWindow = confirm('Estàs segur que vol eliminar aquesta foto?')
1048
1049 if (confirmWindow == true) {
1050 this.objectJuratsPreview[fotoName] = '';
1051 this.objectJurats[fotoName] = '';
1052 this.logValidationErrors()
1053 }
1054
1055 } else {
1056 let confirmWindow = confirm('Estàs segur que vol eliminar aquesta foto?')
1057
1058 if (confirmWindow == true) {
1059 this.fotosRepte[fotoName] = '';
1060 this.fotosReptePreview[fotoName] = '';
1061 }
1062 }
1063
1064 this.logValidationErrors()
1065 }
1066
1067 eliminarFotoArray(fotoName, i) {
1068 let str = fotoName;
1069
1070 //Separem el nom de foto
1071 let arraySplit = str.split(/([0-9]+)/) //fotoPremi
1072 let number = Number(arraySplit[1]); //0
1073
1074 if (arraySplit[0] == 'fotoPremi') {
1075
1076 let confirmWindow = confirm('Estàs segur que vols eliminar aquests premi?')
1077 if (confirmWindow == true) {
1078 this.loopObjectFotosPreview(number, arraySplit[0]);
1079 this.loopObjectFotos(number, arraySplit[0]);
1080 this.removePremiButtonClick(i);
1081 }
1082 }
1083 else if (arraySplit[0] == 'fotoSolucio') {
1084
1085 let confirmWindow = confirm('Estàs segur que vols eliminar aquesta solució?')
1086 if (confirmWindow == true) {
1087 this.loopObjectFotosPreviewSolucio(number, arraySplit[0]);
1088 this.loopObjectFotosSolucio(number, arraySplit[0]);
1089 this.removeSolucioButtonClick(i);
1090 }
1091 }
1092 else if (arraySplit[0] == 'fotoPartner') {
1093
1094 let confirmWindow = confirm('Estàs segur que vols eliminar aquest partner?')
1095 if (confirmWindow == true) {
1096 this.loopObjectFotosPreviewPartner(number, arraySplit[0]);
1097 this.loopObjectFotosPartner(number, arraySplit[0]);
1098 this.removePartnerButtonClick(i);
1099 this.logValidationErrors();
1100 }
1101
1102 }
1103 else if (arraySplit[0] == 'fotoJurat') {
1104
1105 let confirmWindow = confirm('Estàs segur que vols eliminar aquest jurat?')
1106 if (confirmWindow == true) {
1107 this.loopObjectFotosPreviewJurat(number, arraySplit[0]);
1108 this.loopObjectFotosJurat(number, arraySplit[0]);
1109 this.removeJuratButtonClick(i);
1110 this.logValidationErrors()
1111 }
1112
1113 }
1114
1115 this.logValidationErrors()
1116
1117 }
1118
1119 addPremiToObject(inputName) {
1120 let str = inputName;
1121 let arraySplit = str.split(/([0-9]+)/)
1122
1123 if (arraySplit[0] == 'fotoPremi') {
1124 if (!this.objectFotosPreview[inputName]) {
1125 this.objectFotosPreview[inputName] = '';
1126 this.objectFotos[inputName] = '';
1127 }
1128 }
1129 else if (arraySplit[0] == 'fotoSolucio') {
1130 if (!this.objectSolucionsPreview[inputName]) {
1131 this.objectSolucionsPreview[inputName] = '';
1132 this.objectSolucions[inputName] = '';
1133 }
1134 }
1135 else if (arraySplit[0] == 'fotoPartner') {
1136 if (!this.objectPartnersPreview[inputName]) {
1137 this.objectPartnersPreview[inputName] = '';
1138 this.objectPartners[inputName] = '';
1139 }
1140 }
1141 else if (arraySplit[0] == 'fotoJurat') {
1142 if (!this.objectJuratsPreview[inputName]) {
1143 this.objectJuratsPreview[inputName] = '';
1144 this.objectJurats[inputName] = '';
1145 }
1146 }
1147
1148 }
1149
1150
1151
1152 loopObjectFotosPreview(number, valueName) {
1153 console.log("FOTOPREMI QUE VOLEM ELIMINAR:" + valueName + number);
1154 let arrayLength = Object.keys(this.objectFotosPreview).length - 1
1155
1156 for (const [key, value] of Object.entries(this.objectFotosPreview)) {
1157 let index = key.split(/([0-9]+)/)[1];
1158 console.log("LOOP NÚMERO: " + index)
1159 if (index < number) {
1160 console.log("PREMI INFERIOR AL QUE VOLEM ELIMINAR")
1161 }
1162 if (index == number) {
1163 console.log("PREMI QUE VOLEM ELIMINAR")
1164 }
1165 if (index > number) {
1166 console.log("PREMI QUE VOLEM RESTAR")
1167 let resta = Number(index) - 1;
1168 let stringPassada = valueName + Number(index)
1169 let stringRestada = valueName + resta
1170
1171 console.log("NUMERO ES MODIFICA DE: " + stringPassada + " A: " + stringRestada)
1172
1173 this.objectFotosPreview[stringRestada] = this.objectFotosPreview[stringPassada]
1174
1175 }
1176 }
1177 console.log("ULTIM OBJECTE: " + valueName + arrayLength)
1178 console.log("ELIMINANT ULTIM OBJECTE...")
1179 delete this.objectFotosPreview[valueName + arrayLength];
1180 console.log("ArrayObject despres de manipular: ", this.objectFotosPreview)
1181 }
1182
1183 loopObjectFotos(number, valueName) {
1184
1185 console.log("FOTOPREMI QUE VOLEM ELIMINAR:" + valueName + number);
1186 let arrayLength = Object.keys(this.objectFotos).length - 1
1187
1188 for (const [key, value] of Object.entries(this.objectFotos)) {
1189 let index = key.split(/([0-9]+)/)[1];
1190 console.log("LOOP NÚMERO: " + index)
1191 if (index < number) {
1192 console.log("PREMI INFERIOR AL QUE VOLEM ELIMINAR")
1193 }
1194 if (index == number) {
1195 console.log("PREMI QUE VOLEM ELIMINAR")
1196 }
1197 if (index > number) {
1198 console.log("PREMI QUE VOLEM RESTAR")
1199 let resta = Number(index) - 1;
1200 let stringPassada = valueName + Number(index)
1201 let stringRestada = valueName + resta
1202
1203 console.log("NUMERO ES MODIFICA DE: " + stringPassada + " A: " + stringRestada)
1204
1205 this.objectFotos[stringRestada] = this.objectFotos[stringPassada]
1206
1207 }
1208 }
1209 console.log("ULTIM OBJECTE: " + valueName + arrayLength)
1210 console.log("ELIMINANT ULTIM OBJECTE...")
1211 delete this.objectFotos[valueName + arrayLength];
1212 console.log("ArrayObject despres de manipular: ", this.objectFotos)
1213
1214 }
1215
1216
1217 addPremiFormGroup(): FormGroup {
1218 return this.fb.group({
1219 nomPremi: ['', [Validators.required, Validators.maxLength(255), Validators.minLength(3)]],
1220 dotacioPremi: ['', [Validators.required, Validators.maxLength(255), Validators.minLength(1)]],
1221 descripcioPremi: ['', [Validators.maxLength(900), Validators.minLength(3)]],
1222 fotoPremi: ['']
1223 })
1224 }
1225
1226 addSolucioFormGroup(): FormGroup {
1227 return this.fb.group({
1228 nomSolucio: ['', [Validators.required, Validators.maxLength(255), Validators.minLength(3)]],
1229 descripcioSolucio: ['', [Validators.required, Validators.maxLength(900), Validators.minLength(3)]],
1230 fotoSolucio: ['']
1231 })
1232 }
1233
1234 addPartnerFormGroup(): FormGroup {
1235 return this.fb.group({
1236 nomPartner: ['', [Validators.maxLength(255), Validators.minLength(3)]],
1237 breuDescripcioPartner: ['', [Validators.maxLength(900), Validators.minLength(3)]],
1238 logoPartner: [''],
1239 })
1240 }
1241
1242 addJuratFormGroup(): FormGroup {
1243 return this.fb.group({
1244 nomCognomsJurat: ['', [Validators.maxLength(255), Validators.minLength(3)]],
1245 biografiaJurat: ['', [Validators.maxLength(900), Validators.minLength(3)]],
1246 fotoJurat: [''],
1247 })
1248 }
1249
1250 addPreguntaFormGroup(): FormGroup {
1251 return this.fb.group({
1252 pregunta: ['', [Validators.required, Validators.maxLength(255), Validators.minLength(3)]],
1253 resposta: ['', [Validators.required, Validators.maxLength(2000), Validators.minLength(3)]],
1254 })
1255 }
1256
1257 addPremiButtonClick(): void {
1258 (<FormArray>this.repteForm.get('premiArray')).push(this.addPremiFormGroup());
1259 }
1260
1261 addSolucioButtonClick(): void {
1262 (<FormArray>this.repteForm.get('solucioArray')).push(this.addSolucioFormGroup());
1263 }
1264
1265 addPartnerButtonClick(): void {
1266 (<FormArray>this.repteForm.get('partnerArray')).push(this.addPartnerFormGroup());
1267 }
1268
1269 addJuratButtonClick(): void {
1270 (<FormArray>this.repteForm.get('juratArray')).push(this.addJuratFormGroup());
1271 }
1272
1273 addPreguntaButtonClick(): void {
1274 (<FormArray>this.repteForm.get('preguntaArray')).push(this.addPreguntaFormGroup());
1275 }
1276
1277 removePremiButtonClick(partnerGroupIndex: number): void {
1278 (<FormArray>this.repteForm.get('premiArray')).removeAt(partnerGroupIndex)
1279 }
1280
1281 removeSolucioButtonClick(solucioGroupIndex: number): void {
1282 (<FormArray>this.repteForm.get('solucioArray')).removeAt(solucioGroupIndex)
1283 }
1284
1285 removePartnerButtonClick(partnerGroupIndex: number): void {
1286 (<FormArray>this.repteForm.get('partnerArray')).removeAt(partnerGroupIndex)
1287 }
1288
1289 removeJuratButtonClick(partnerGroupIndex: number): void {
1290 (<FormArray>this.repteForm.get('juratArray')).removeAt(partnerGroupIndex)
1291 }
1292
1293 removePreguntaButtonClick(partnerGroupIndex: number): void {
1294 (<FormArray>this.repteForm.get('preguntaArray')).removeAt(partnerGroupIndex)
1295 }
1296
1297 @HostListener('window:beforeunload', ['$event'])
1298 public onPageUnload($event: BeforeUnloadEvent) {
1299
1300 if (this.repteForm.dirty && !this.formDone) {
1301 $event.returnValue = true;
1302 }
1303 }
1304
1305 ngOnDestroy() {
1306 this.subscriptionForm$?.unsubscribe()
1307
1308 }
1309
1310 checkboxvalues() {
1311 console.log("CHECKBOXES")
1312 console.log(this.repteForm.get('checkboxGroup').value)
1313 console.log(this.repteForm.get('checkboxGroup').value.empresesCheckbox)
1314 }
1315
1316 appendRepte(): FormData {
1317
1318 const formData = new FormData();
1319
1320 if (this.repteForm.get('descripcioBreuRepte').value) {
1321 formData.append('descripcio_short', this.repteForm.get('descripcioBreuRepte').value);
1322 }
1323
1324 if (this.repteForm.get('descripcioDetalladaRepte').value) {
1325 formData.append('descripcio_long', this.repteForm.get('descripcioDetalladaRepte').value);
1326 }
1327
1328 if (this.repteForm.get('nomRepte').value) {
1329 formData.append('nom', this.repteForm.get('nomRepte').value);
1330 }
1331
1332 if (this.repteForm.get('videoSolucio').value) {
1333 formData.append('url_video', this.repteForm.get('videoSolucio').value);
1334
1335 }
1336
1337 if (this.radioValue == "equip") {
1338
1339 formData.append('individual_equip', '1')
1340
1341 if (this.repteForm.get('limitParticipants').value) {
1342
1343 formData.append('limit_participants', this.repteForm.get('limitParticipants').value)
1344
1345 }
1346
1347 } else {
1348 formData.append('individual_equip', '0');
1349
1350 }
1351
1352 if (this.radioToSValue == "custom") {
1353 formData.append('bases_legals', '1')
1354 if (this.repteForm.get('customTOS').value) {
1355 formData.append('bases_legals_personals', this.repteForm.get('customTOS').value)
1356 }
1357 } else {
1358 formData.append('bases_legals', '0');
1359 }
1360
1361 if (this.repteForm.get('datesGroup').get('dataInici').value) {
1362 let iniciDate = this.datepipe.transform(this.repteForm.get('datesGroup').get('dataInici').value, 'dd/MM/yyyy')
1363 formData.append('data_inici', iniciDate)
1364 }
1365
1366 if (this.repteForm.get('datesGroup').get('dataFinalitzacio').value) {
1367 let finalDate = this.datepipe.transform(this.repteForm.get('datesGroup').get('dataFinalitzacio').value, 'dd/MM/yyyy')
1368 formData.append('data_final', finalDate)
1369 }
1370
1371 formData.append('participants[empreses]', (this.repteForm.get('checkboxGroup').value.empresesCheckbox))
1372 formData.append('participants[startups]', this.repteForm.get('checkboxGroup').value.startupsCheckbox)
1373 formData.append('participants[estudiants]', this.repteForm.get('checkboxGroup').value.estudiantsCheckbox)
1374 formData.append('participants[experts]', this.repteForm.get('checkboxGroup').value.expertsCheckbox)
1375
1376 // APPENDING PREMI
1377 for (var i = 0; i < (<FormArray>this.repteForm.get('premiArray')).controls.length; i++) {
1378
1379 if (this.repte.premis[i]) {
1380 formData.append(`idpremi[${i}]`, this.repte.premis[i].idpremi);
1381 }
1382
1383 if (this.repteForm.get('premiArray').value[i].nomPremi) {
1384 formData.append(`premi_nom[${i}]`, this.repteForm.get('premiArray').value[i].nomPremi);
1385 } else {
1386 formData.append(`premi_nom[${i}]`, '');
1387
1388 }
1389 if (this.repteForm.get('premiArray').value[i].dotacioPremi) {
1390 formData.append(`premi_dotacio[${i}]`, this.repteForm.get('premiArray').value[i].dotacioPremi);
1391 }
1392 if (this.repteForm.get('premiArray').value[i].descripcioPremi) {
1393 formData.append(`premi_descripcio[${i}]`, this.repteForm.get('premiArray').value[i].descripcioPremi);
1394 }
1395
1396 let premiFotoName = 'fotoPremi' + i;
1397
1398 if (this.objectFotos[premiFotoName]) {
1399 if (this.repteForm.get('premiArray').value[i].fotoPremi) {
1400 formData.append(`premi_url_photo[${i}]`, this.objectFotos[premiFotoName]);
1401 }
1402 }
1403 }
1404
1405 //APPENDING SOLUCIO
1406 for (var i = 0; i < (<FormArray>this.repteForm.get('solucioArray')).controls.length; i++) {
1407
1408 if (this.repte.solucions[i]) {
1409 formData.append(`idsolucio[${i}]`, this.repte.solucions[i].idsolucio);
1410 }
1411
1412 if (this.repteForm.get('solucioArray').value[i].nomSolucio) {
1413 formData.append(`solucio_nom[${i}]`, this.repteForm.get('solucioArray').value[i].nomSolucio);
1414 } else {
1415 formData.append(`solucio_nom[${i}]`, '');
1416
1417 }
1418 if (this.repteForm.get('solucioArray').value[i].descripcioSolucio) {
1419 formData.append(`solucio_descripcio[${i}]`, this.repteForm.get('solucioArray').value[i].descripcioSolucio);
1420 }
1421
1422 let solucioFotoName = 'fotoSolucio' + i;
1423
1424 if (this.objectSolucions[solucioFotoName]) {
1425 if (this.repteForm.get('solucioArray').value[i].fotoSolucio) {
1426 formData.append(`solucio_url_photo[${i}]`, this.objectSolucions[solucioFotoName]);
1427 }
1428 }
1429 }
1430
1431 //APPENDING PARTNER
1432 for (var i = 0; i < (<FormArray>this.repteForm.get('partnerArray')).controls.length; i++) {
1433
1434 if (this.repte.partners[i]) {
1435 formData.append(`idpartner[${i}]`, this.repte.partners[i].idpartner);
1436 }
1437
1438 if (this.repteForm.get('partnerArray').value[i].nomPartner) {
1439 formData.append(`partner_nom[${i}]`, this.repteForm.get('partnerArray').value[i].nomPartner);
1440 } else {
1441 formData.append(`partner_nom[${i}]`, '');
1442
1443 }
1444 if (this.repteForm.get('partnerArray').value[i].breuDescripcioPartner) {
1445 formData.append(`partner_descripcio[${i}]`, this.repteForm.get('partnerArray').value[i].breuDescripcioPartner);
1446 }
1447
1448 let partnerFotoName = 'fotoPartner' + i;
1449
1450 if (this.objectPartners[partnerFotoName]) {
1451 if (this.repteForm.get('partnerArray').value[i].logoPartner) {
1452 formData.append(`partner_url_logo[${i}]`, this.objectPartners[partnerFotoName]);
1453 }
1454 }
1455 }
1456
1457 //APPENDING JURAT
1458 for (var i = 0; i < (<FormArray>this.repteForm.get('juratArray')).controls.length; i++) {
1459
1460 if (this.repte.jurats[i]) {
1461 formData.append(`idjurat[${i}]`, this.repte.jurats[i].idjurat);
1462 }
1463
1464 if (this.repteForm.get('juratArray').value[i].nomCognomsJurat) {
1465 formData.append(`jurat_nom[${i}]`, this.repteForm.get('juratArray').value[i].nomCognomsJurat);
1466 } else {
1467 formData.append(`jurat_nom[${i}]`, '');
1468
1469 }
1470 if (this.repteForm.get('juratArray').value[i].biografiaJurat) {
1471 formData.append(`jurat_bio[${i}]`, this.repteForm.get('juratArray').value[i].biografiaJurat);
1472 }
1473
1474 let juratFotoName = 'fotoJurat' + i;
1475
1476 if (this.objectJurats[juratFotoName]) {
1477 if (this.repteForm.get('juratArray').value[i].fotoJurat) {
1478 formData.append(`jurat_url_photo[${i}]`, this.objectJurats[juratFotoName]);
1479 }
1480 }
1481 }
1482
1483 //APPENDING FAQ
1484 for (var i = 0; i < (<FormArray>this.repteForm.get('preguntaArray')).controls.length; i++) {
1485 if (this.repteForm.get('preguntaArray').value[i].pregunta) {
1486 formData.append(`faq_pregunta[${i}]`, this.repteForm.get('preguntaArray').value[i].pregunta);
1487 }
1488 if (this.repteForm.get('preguntaArray').value[i].resposta) {
1489 formData.append(`faq_resposta[${i}]`, this.repteForm.get('preguntaArray').value[i].resposta);
1490 }
1491 }
1492
1493 //APPENDING RECURSOS
1494 if (this.pdfArray.length) {
1495 for (let index = 0; index < this.pdfArray.length; index++) {
1496 if (this.pdfChanged) {
1497
1498 const file = this.pdfArray[index];
1499
1500 formData.append(`recurs_nom[${index}]`, file.name);
1501 formData.append(`recurs_url_fitxer[${index}]`, file);
1502 }
1503 }
1504 }
1505
1506 //APPENDING FOTOS REPTE
1507 if (this.fotosRepte.fotoPortada) {
1508 if (this.repteForm.get('fotoPortada').value) {
1509 formData.append(`url_photo_main`, this.fotosRepte.fotoPortada);
1510 }
1511 }
1512
1513 if (this.fotosRepte.fotoRepresentativa1) {
1514 if (this.repteForm.get('fotoRepresentativa1').value) {
1515 formData.append(`url_photo_1`, this.fotosRepte.fotoRepresentativa1);
1516 }
1517 }
1518
1519 if (this.fotosRepte.fotoRepresentativa2) {
1520 if (this.repteForm.get('fotoRepresentativa2').value) {
1521 formData.append(`url_photo_2`, this.fotosRepte.fotoRepresentativa2);
1522 }
1523 }
1524
1525 if (this.fotosRepte.fotoRepresentativa3) {
1526 if (this.repteForm.get('fotoRepresentativa3').value) {
1527 formData.append(`url_photo_3`, this.fotosRepte.fotoRepresentativa3);
1528 }
1529 }
1530
1531
1532 return formData;
1533 }
1534
1535 // desaBorrador() {
1536
1537 // if (!this.repteForm.get('nomRepte').value) {
1538
1539 // if (!this.formErrors.nomRepte) {
1540 // this.formErrors.nomRepte += this.validationMessages.nomRepte.required + ' ';
1541 // }
1542
1543 // if (!this.formErrors.campsErronis) {
1544 // this.formErrors.campsErronis += this.validationMessages.campsErronis.errors + ' ';
1545 // }
1546
1547 // } else if (this.repteForm.get('nomRepte').value.length < 3) {
1548
1549 // if (!this.formErrors.nomRepte) {
1550 // this.formErrors.nomRepte += this.validationMessages.nomRepte.minlength + ' ';
1551 // }
1552
1553 // if (!this.formErrors.campsErronis) {
1554 // this.formErrors.campsErronis += this.validationMessages.campsErronis.errors + ' ';
1555 // }
1556
1557 // } else if (this.repteForm.get('nomRepte').value.length > 255) {
1558
1559 // if (!this.formErrors.nomRepte) {
1560 // this.formErrors.nomRepte += this.validationMessages.nomRepte.maxlength + ' ';
1561 // }
1562
1563 // if (!this.formErrors.campsErronis) {
1564 // this.formErrors.campsErronis += this.validationMessages.campsErronis.errors + ' ';
1565 // }
1566
1567 // } else {
1568 // this.formDone = true;
1569
1570 // if (this.formErrors.campsErronis) {
1571 // this.formErrors.campsErronis = '';
1572 // }
1573
1574 // let formData: any = this.appendRepte();
1575
1576 // for (var value of formData.values()) {
1577 // console.log(value);
1578 // }
1579
1580 // this.subscriptionHttp1$ = this.httpClient.editRepteEsborrany(this.idRepte, formData)
1581 // .pipe(first())
1582 // .subscribe(
1583 // data => {
1584 // console.log(data)
1585 // if (data.code == 1) {
1586 // this.success = true;
1587 // this.actualitzat = true;
1588 // // let currentUserId = JSON.parse(localStorage.getItem('currentUser')).idUser;
1589 // // this.router.navigate([`/perfil/${currentUserId}`])
1590 // }
1591 // });
1592 // }
1593
1594
1595
1596
1597 // }
1598
1599
1600 onRepteSubmit() {
1601 window.scrollTo(0, 0)
1602
1603 this.checkUntouched = true;
1604 console.log(this.repteForm.get('checkboxGroup'))
1605 if (!this.repteForm.valid) {
1606 console.log(this.repteForm.valid)
1607 for (const field in this.repteForm.controls) { // 'field' is a string
1608 const control = this.repteForm.get(field).errors; // 'control' is a FormControl
1609 console.log(field, control)
1610 }
1611 if (!this.formErrors.campsErronis) {
1612 this.formErrors.campsErronis += this.validationMessages.campsErronis.errors + ' ';
1613 }
1614
1615 this.logValidationErrorsUntouched()
1616
1617 } else {
1618 let confirmWindow = confirm('Està segur que vol actualitzar aquest repte?')
1619
1620 if (confirmWindow == true) {
1621 this.formDone = true;
1622
1623 if (this.formErrors.campsErronis) {
1624 this.formErrors.campsErronis = '';
1625 }
1626
1627 let formData: any = this.appendRepte();
1628
1629 for (var value of formData.values()) {
1630 console.log(value);
1631 }
1632
1633 this.subscriptionHttp1$ = this.httpClient.editRepte(this.idRepte, formData)
1634 .pipe(first())
1635 .subscribe(
1636 data => {
1637 if (data.code == 1) {
1638 window.scrollTo(0, 0)
1639 this.toastr.success('Repte actualitzat i enviat per revisar!', 'Enviat')
1640 this.success = true;
1641 this.enviat = true;
1642 }
1643
1644 });
1645 }
1646
1647 }
1648 }
1649
1650 deleteRepte() {
1651 this.subscriptionHttp1$ = this.httpClient.deleteRepte(this.idRepte)
1652 .pipe(first())
1653 .subscribe(
1654 data => {
1655 if (data.code == 1) {
1656 this.success = true;
1657 this.eliminat = true;
1658 this.toastr.success('Repte eliminat correctament', 'Eliminat')
1659
1660 }
1661
1662 });
1663 }
1664
1665 logValidationErrorsUntouched(group: FormGroup = this.repteForm): void {
1666 Object.keys(group.controls).forEach((key: string) => {
1667 const abstractControl = group.get(key);
1668
1669 this.formErrors[key] = '';
1670 if (abstractControl && !abstractControl.valid) {
1671 const messages = this.validationMessages[key];
1672
1673 for (const errorKey in abstractControl.errors) {
1674 if (errorKey) {
1675 this.formErrors[key] += messages[errorKey] + ' ';
1676 }
1677 }
1678 }
1679
1680 if (abstractControl instanceof FormGroup) {
1681 this.logValidationErrorsUntouched(abstractControl);
1682 }
1683 // if (abstractControl instanceof FormArray) {
1684 // for (const control of abstractControl.controls) {
1685 // if (control instanceof FormGroup) {
1686 // this.logValidationErrors(control);
1687 // }
1688 // }
1689 // }
1690 })
1691 }
1692
1693
1694 loopObjectFotosPreviewSolucio(number, valueName) {
1695 let arrayLength = Object.keys(this.objectSolucionsPreview).length - 1
1696
1697 for (const [key, value] of Object.entries(this.objectSolucionsPreview)) {
1698 let index = key.split(/([0-9]+)/)[1];
1699 if (index < number) {
1700 console.log("PREMI INFERIOR AL QUE VOLEM ELIMINAR")
1701 }
1702 if (index == number) {
1703 console.log("PREMI QUE VOLEM ELIMINAR")
1704 }
1705 if (index > number) {
1706 console.log("PREMI QUE VOLEM RESTAR")
1707 let resta = Number(index) - 1;
1708 let stringPassada = valueName + Number(index)
1709 let stringRestada = valueName + resta
1710
1711 console.log("NUMERO ES MODIFICA DE: " + stringPassada + " A: " + stringRestada)
1712
1713 this.objectSolucionsPreview[stringRestada] = this.objectSolucionsPreview[stringPassada]
1714
1715 }
1716 }
1717 console.log("ULTIM OBJECTE: " + valueName + arrayLength)
1718 console.log("ELIMINANT ULTIM OBJECTE...")
1719 delete this.objectSolucionsPreview[valueName + arrayLength];
1720 console.log("ArrayObject despres de manipular: ", this.objectSolucionsPreview)
1721 }
1722
1723 loopObjectFotosSolucio(number, valueName) {
1724 let arrayLength = Object.keys(this.objectSolucions).length - 1
1725
1726 for (const [key, value] of Object.entries(this.objectSolucions)) {
1727 let index = key.split(/([0-9]+)/)[1];
1728 console.log("LOOP NÚMERO: " + index)
1729 if (index < number) {
1730 console.log("PREMI INFERIOR AL QUE VOLEM ELIMINAR")
1731 }
1732 if (index == number) {
1733 console.log("PREMI QUE VOLEM ELIMINAR")
1734 }
1735 if (index > number) {
1736 console.log("PREMI QUE VOLEM RESTAR")
1737 let resta = Number(index) - 1;
1738 let stringPassada = valueName + Number(index)
1739 let stringRestada = valueName + resta
1740
1741 console.log("NUMERO ES MODIFICA DE: " + stringPassada + " A: " + stringRestada)
1742
1743 this.objectSolucions[stringRestada] = this.objectSolucions[stringPassada]
1744
1745 }
1746 }
1747 console.log("ULTIM OBJECTE: " + valueName + arrayLength)
1748 console.log("ELIMINANT ULTIM OBJECTE...")
1749 delete this.objectSolucions[valueName + arrayLength];
1750 console.log("ArrayObject despres de manipular: ", this.objectSolucions)
1751
1752 }
1753
1754 loopObjectFotosPreviewPartner(number, valueName) {
1755 let arrayLength = Object.keys(this.objectPartnersPreview).length - 1
1756
1757 for (const [key, value] of Object.entries(this.objectPartnersPreview)) {
1758 let index = key.split(/([0-9]+)/)[1];
1759 console.log("LOOP NÚMERO: " + index)
1760 if (index < number) {
1761 console.log("PREMI INFERIOR AL QUE VOLEM ELIMINAR")
1762 }
1763 if (index == number) {
1764 console.log("PREMI QUE VOLEM ELIMINAR")
1765 }
1766 if (index > number) {
1767 console.log("PREMI QUE VOLEM RESTAR")
1768 let resta = Number(index) - 1;
1769 let stringPassada = valueName + Number(index)
1770 let stringRestada = valueName + resta
1771
1772 console.log("NUMERO ES MODIFICA DE: " + stringPassada + " A: " + stringRestada)
1773
1774 this.objectPartnersPreview[stringRestada] = this.objectPartnersPreview[stringPassada]
1775
1776 }
1777 }
1778 console.log("ULTIM OBJECTE: " + valueName + arrayLength)
1779 console.log("ELIMINANT ULTIM OBJECTE...")
1780 delete this.objectPartnersPreview[valueName + arrayLength];
1781 console.log("ArrayObject despres de manipular: ", this.objectPartnersPreview)
1782 }
1783
1784 loopObjectFotosPartner(number, valueName) {
1785
1786 console.log("FOTOPREMI QUE VOLEM ELIMINAR:" + valueName + number);
1787 let arrayLength = Object.keys(this.objectPartners).length - 1
1788
1789 for (const [key, value] of Object.entries(this.objectPartners)) {
1790 let index = key.split(/([0-9]+)/)[1];
1791 console.log("LOOP NÚMERO: " + index)
1792 if (index < number) {
1793 console.log("PREMI INFERIOR AL QUE VOLEM ELIMINAR")
1794 }
1795 if (index == number) {
1796 console.log("PREMI QUE VOLEM ELIMINAR")
1797 }
1798 if (index > number) {
1799 console.log("PREMI QUE VOLEM RESTAR")
1800 let resta = Number(index) - 1;
1801 let stringPassada = valueName + Number(index)
1802 let stringRestada = valueName + resta
1803
1804 console.log("NUMERO ES MODIFICA DE: " + stringPassada + " A: " + stringRestada)
1805
1806 this.objectPartners[stringRestada] = this.objectPartners[stringPassada]
1807
1808 }
1809 }
1810 console.log("ULTIM OBJECTE: " + valueName + arrayLength)
1811 console.log("ELIMINANT ULTIM OBJECTE...")
1812 delete this.objectPartners[valueName + arrayLength];
1813 console.log("ArrayObject despres de manipular: ", this.objectPartners)
1814
1815 }
1816
1817 loopObjectFotosPreviewJurat(number, valueName) {
1818 console.log("FOTOPREMI QUE VOLEM ELIMINAR:" + valueName + number);
1819 let arrayLength = Object.keys(this.objectJuratsPreview).length - 1
1820
1821 for (const [key, value] of Object.entries(this.objectJuratsPreview)) {
1822 let index = key.split(/([0-9]+)/)[1];
1823 console.log("LOOP NÚMERO: " + index)
1824 if (index < number) {
1825 console.log("PREMI INFERIOR AL QUE VOLEM ELIMINAR")
1826 }
1827 if (index == number) {
1828 console.log("PREMI QUE VOLEM ELIMINAR")
1829 }
1830 if (index > number) {
1831 console.log("PREMI QUE VOLEM RESTAR")
1832 let resta = Number(index) - 1;
1833 let stringPassada = valueName + Number(index)
1834 let stringRestada = valueName + resta
1835
1836 console.log("NUMERO ES MODIFICA DE: " + stringPassada + " A: " + stringRestada)
1837
1838 this.objectJuratsPreview[stringRestada] = this.objectJuratsPreview[stringPassada]
1839
1840 }
1841 }
1842 console.log("ULTIM OBJECTE: " + valueName + arrayLength)
1843 console.log("ELIMINANT ULTIM OBJECTE...")
1844 delete this.objectJuratsPreview[valueName + arrayLength];
1845 console.log("ArrayObject despres de manipular: ", this.objectJuratsPreview)
1846 }
1847
1848 loopObjectFotosJurat(number, valueName) {
1849
1850 console.log("FOTOPREMI QUE VOLEM ELIMINAR:" + valueName + number);
1851 let arrayLength = Object.keys(this.objectJurats).length - 1
1852
1853 for (const [key, value] of Object.entries(this.objectJurats)) {
1854 let index = key.split(/([0-9]+)/)[1];
1855 console.log("LOOP NÚMERO: " + index)
1856 if (index < number) {
1857 console.log("PREMI INFERIOR AL QUE VOLEM ELIMINAR")
1858 }
1859 if (index == number) {
1860 console.log("PREMI QUE VOLEM ELIMINAR")
1861 }
1862 if (index > number) {
1863 console.log("PREMI QUE VOLEM RESTAR")
1864 let resta = Number(index) - 1;
1865 let stringPassada = valueName + Number(index)
1866 let stringRestada = valueName + resta
1867
1868 console.log("NUMERO ES MODIFICA DE: " + stringPassada + " A: " + stringRestada)
1869
1870 this.objectJurats[stringRestada] = this.objectJurats[stringPassada]
1871
1872 }
1873 }
1874 console.log("ULTIM OBJECTE: " + valueName + arrayLength)
1875 console.log("ELIMINANT ULTIM OBJECTE...")
1876 delete this.objectJurats[valueName + arrayLength];
1877 console.log("ArrayObject despres de manipular: ", this.objectJurats)
1878
1879 }
1880 }
1881
1882
1883 // function dateGreaterThan(control: AbstractControl): { [key: string]: boolean } | null {
1884
1885 // if (this.repteForm.get('dataFinalitzacio').value && this.repteForm.get('dataFinalitzacio').value) {
1886
1887 // let dataFinal = new Date(this.repteForm.get('dataFinalitzacio').value);
1888 // let dataInici = new Date(this.repteForm.get('dataInici').value);
1889
1890 // if (dataInici > dataFinal) {
1891 // return { 'dateGreaterThan': true }
1892 // }
1893 // }
1894
1895 // return null;
1896
1897 // };
1898
1899
1900 function dateShorterThanToday(control: AbstractControl): { [key: string]: any } | null {
1901 let date = new Date(control.value);
1902 let currentDate = new Date();
1903
1904 if (control.value) {
1905 if (date > currentDate) {
1906 return null;
1907 }
1908 else {
1909 return { dateShorterThanToday: true }
1910 }
1911 } else {
1912 return null;
1913 }
1914
1915 }
1916
1917
1918
1919 function dateString(date) {
1920 var any = date.getFullYear();
1921 var mes = date.getMonth() + 1;
1922 var dia = date.getDate();
1923
1924 return dia + "/" + mes + "/" + any
1925 }
1926
1927
1928
1929 function requireCheckboxesToBeCheckedValidator(minRequired = 1): ValidatorFn {
1930 return function validate(formGroup: FormGroup) {
1931 let checked = 0;
1932
1933 Object.keys(formGroup.controls).forEach(key => {
1934 const control = formGroup.controls[key];
1935
1936 if (control.value === true) {
1937 checked++;
1938 }
1939 });
1940
1941 if (checked < minRequired) {
1942 return {
1943 requireCheckboxesToBeChecked: true,
1944 };
1945 }
1946
1947 return null;
1948 };
1949 }
1950
1951 function dataIniciBiggerThanFinal(): ValidatorFn {
1952 return function validate(form: FormGroup) {
1953 let startDate = new Date(form.value.dataInici);
1954 let endDate = new Date(form.value.dataFinalitzacio);
1955
1956 if (startDate >= endDate) {
1957 return {
1958 dataIniciBiggerThanFinal: true
1959 };
1960 }
1961
1962 return null;
1963 };
1964 }
1965
Enlace
El enlace para compartir es: