import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { AlertController, ModalController } from '@ionic/angular'; import * as moment from 'moment'; import { Attachment } from 'src/app/models/attachment.model'; import { EventPerson } from 'src/app/models/eventperson.model'; import { SearchList } from 'src/app/models/search-document'; import { SearchPage } from 'src/app/pages/search/search.page'; import { AttachmentsService } from 'src/app/services/attachments.service'; import { EventsService } from 'src/app/services/events.service'; import { ProcessesService } from 'src/app/services/processes.service'; import { ToastService } from 'src/app/services/toast.service'; import { NgxMatDateFormats } from '@angular-material-components/datetime-picker'; import { removeDuplicate } from 'src/plugin/removeDuplicate.js' import { EventToApproveEdit } from 'src/app/models/event.model'; import { ThemeService } from 'src/app/services/theme.service' import { Router } from '@angular/router'; const CUSTOM_DATE_FORMATS: NgxMatDateFormats = { parse: { dateInput: "YYYY-MMMM-DD HH:mm" }, display: { dateInput: "DD MMM YYYY H:mm", monthYearLabel: "MMM YYYY", dateA11yLabel: "LL", monthYearA11yLabel: "MMMM YYYY" } } @Component({ selector: 'app-edit-event-to-approve', templateUrl: './edit-event-to-approve.page.html', styleUrls: ['./edit-event-to-approve.page.scss'], }) export class EditEventToApprovePage implements OnInit { public date: any; public disabled = false; public showSpinners = true; public showSeconds = false; public touchUi = false; public enableMeridian = false; public minDate = new Date() public endMinDate = new Date(new Date().getTime() + 15 * 60000); public maxDate: any; public stepHour = 1; public stepMinute = 5; public stepSecond = 5; public dateControlStart = new FormControl(moment("DD MM YYYY hh")); public dateControlEnd = new FormControl(moment("DD MM YYYY hh")); recurringTypes: any; selectedRecurringType: any; showLoader = false get dateStart () { return this.dateControlStart.value } get dateEnd () { return this.dateControlEnd.value } @ViewChild('picker') picker: any; @ViewChild('fim') fim: any; @ViewChild('inicio') inicio: any; @ViewChild('picker1') picker1: any; loadedAttachments: Attachment[]= [] eventProcess = { serialNumber: "", taskStartDate: "", workflowInstanceDataFields:{ Body: "", OccurrenceType: '', Category: '', LastOccurrence: new Date(), IsRecurring: false, ParticipantsList: [], Agenda: '', EndDate: '', Location: '', Subject: '', InstanceId: '', EventType: '', StartDate: '', MDEmail: '', MDName: '', IsAllDayEvent: false, Message: '', Status: '' } } show = false isRecurring:string; isEventEdited: boolean; profile:string; eventAttendees: EventPerson[]; loadedEventAttachments: Attachment[]; adding: "intervenient" | "CC" = "intervenient"; showAttendees = false; InstanceId: string; Form: FormGroup; validateFrom = false @Output() openAttendeesComponent = new EventEmitter(); @Output() clearContact = new EventEmitter(); @Output() setIntervenient = new EventEmitter(); @Output() setIntervenientCC = new EventEmitter(); @Output() closeComponent = new EventEmitter(); @Output() closeEventToApprove = new EventEmitter(); @Output() approveEventDismiss = new EventEmitter(); @Input() saveData: any; @Input() serialNumber: string @Input() taskParticipants: EventPerson[]; @Input() taskParticipantsCc: EventPerson[]; constructor( private modalController: ModalController, private eventsService: EventsService, public alertController: AlertController, private attachmentsService: AttachmentsService, private processes:ProcessesService, private toastService: ToastService, public ThemeService: ThemeService, private router: Router, ) { this.isEventEdited = false; } ngOnInit() { if(this.restoreTemporaryData()){ this.setOtherData() } else { this.getTask(); } this.getRecurrenceTypes(); } async getTask() { this.processes.GetTask(this.serialNumber).subscribe( (result) => { this.eventProcess = result this.eventProcess.workflowInstanceDataFields.LastOccurrence = new Date(this.eventProcess.workflowInstanceDataFields.LastOccurrence) this.restoreDatepickerData() // description let body : any =this.eventProcess.workflowInstanceDataFields.Body.replace(/<[^>]+>/g, '') this.eventProcess.workflowInstanceDataFields.Body = body this.eventProcess.workflowInstanceDataFields.Category = this.eventProcess.workflowInstanceDataFields.EventType this.InstanceId = this.eventProcess.workflowInstanceDataFields.InstanceId this.getAttachments() this.setOtherData() this.saveTemporaryData() }) } getRecurrenceTypes() { this.eventsService.getRecurrenceTypes().subscribe(res=>{ this.recurringTypes = res; }); } onSelectedRecurringChanged(ev:any) { this.calculetedLastOccurrence(ev); if(ev.length > 1) { this.eventProcess.workflowInstanceDataFields.OccurrenceType = ev.filter(data => data != '-1'); } if(ev.length == 0) { this.eventProcess.workflowInstanceDataFields.OccurrenceType = "-1"; } } calculetedLastOccurrence(type:number){ var valor; var opcao: boolean; if (type == 0) { valor = 7; opcao = true; } else if(type == 1){ valor = 30; opcao = true; } else if(type == 2){ valor = 1; opcao = false; }else if(type == 3){ valor = 5; opcao = false; } this.defineLastOccurrence(valor, opcao); } defineLastOccurrence(valor:number, opcao:boolean){ var time = new Date(this.eventProcess.workflowInstanceDataFields.EndDate); if (opcao == true) { time.setDate(time.getDate() + valor); this.eventProcess.workflowInstanceDataFields.LastOccurrence = time; } else { time = new Date( time.getFullYear() + valor, time.getMonth(), time.getDate(), time.getHours(), time.getMinutes() ); this.eventProcess.workflowInstanceDataFields.LastOccurrence = time; } } setOtherData() { if(this.eventProcess.workflowInstanceDataFields.ParticipantsList) { this.eventProcess.workflowInstanceDataFields.ParticipantsList.forEach(e => { if(e.IsRequired) { this.taskParticipants.push(e); } else { this.taskParticipantsCc.push(e); } }) } this.taskParticipants = removeDuplicate(this.taskParticipants) this.taskParticipantsCc = removeDuplicate(this.taskParticipantsCc) if(this.eventProcess.workflowInstanceDataFields.IsRecurring == false) { this.isRecurring = "Não se repete"; } else { this.isRecurring = "Repete"; } this.InstanceId = this.eventProcess.workflowInstanceDataFields.InstanceId this.getAttachments() } close() { window['temp.path:/shared/agenda/edit-event-to-approve.ts'] = {}; this.closeEventToApprove.emit(); this.setIntervenient.emit([]); this.setIntervenientCC.emit([]); this.clearContact.emit(); this.approveEventDismiss.emit({ serialNumber: this.eventProcess.serialNumber, action: "Aprovar", saveData: this.eventProcess }); } runValidation() { this.validateFrom = true } injectValidation() { this.Form = new FormGroup({ Subject: new FormControl(this.eventProcess.workflowInstanceDataFields.Subject, [ Validators.required, // Validators.minLength(4) ]), Location: new FormControl(this.eventProcess.workflowInstanceDataFields.Location, [ Validators.required, ]), //CalendarName: new FormControl(this.postEvent.CalendarName), // Categories: new FormControl(this.postEvent.Categories, [ // Validators.required // ]), dateStart: new FormControl(this.dateStart, [ Validators.required ]), dateEnd: new FormControl(this.dateEnd, [ Validators.required ]), // IsRecurring: new FormControl(this.postEvent.IsRecurring, [ // Validators.required // ]), participantes: new FormControl(this.taskParticipants, [ // Validators.required ]), }) } async save() { this.injectValidation() this.runValidation() if(this.Form.invalid) return false // set dates to eventProcess object this.dateControlStart = new FormControl(moment(new Date(this.eventProcess.workflowInstanceDataFields.StartDate)).add(1, 'hours')); this.dateControlEnd = new FormControl(moment(new Date(this.eventProcess.workflowInstanceDataFields.EndDate)).add(1, 'hours')); // this.restoreDatepickerData() // this.getDatepickerData() this.taskParticipantsCc.forEach( e => { e.IsRequired = false }) this.eventProcess.workflowInstanceDataFields.ParticipantsList = this.taskParticipants.concat(this.taskParticipantsCc) this.eventProcess.workflowInstanceDataFields.ParticipantsList.forEach(e=>{ if(e.hasOwnProperty('$type')) { delete e.$type } }) const event: EventToApproveEdit = { SerialNumber: this.eventProcess.serialNumber, Body: this.eventProcess.workflowInstanceDataFields.Body, Location: this.eventProcess.workflowInstanceDataFields.Location, Subject: this.eventProcess.workflowInstanceDataFields.Subject, StartDate: this.dateControlStart.value, EndDate: this.dateControlEnd.value, ReviewUserComment: '', Agenda: this.eventProcess.workflowInstanceDataFields.Agenda, MDName: this.eventProcess.workflowInstanceDataFields.MDName, MDEmail: this.eventProcess.workflowInstanceDataFields.MDEmail, IsAllDayEvent: this.eventProcess.workflowInstanceDataFields.IsAllDayEvent, Status: this.eventProcess.workflowInstanceDataFields.Status, EventType: this.eventProcess.workflowInstanceDataFields.EventType, IsRecurring: this.eventProcess.workflowInstanceDataFields.IsRecurring, Message: this.eventProcess.workflowInstanceDataFields.Message, EventRecurrence: { Type: this.eventProcess.workflowInstanceDataFields.OccurrenceType || '-1', LastOccurrence: this.eventProcess.workflowInstanceDataFields.LastOccurrence, }, ParticipantsList: this.eventProcess.workflowInstanceDataFields.ParticipantsList, Category: this.eventProcess.workflowInstanceDataFields.Category } try { await this.eventsService.postEventToApproveEdit(event).toPromise() this.close() this.toastService.successMessage('Evento editado'); } catch(e) { this.toastService.badRequest('Evento não editado'); } this.loadedAttachments.forEach((document:any)=>{ if(document['action'] == 'add') { delete document.action this.attachmentsService.setEventAttachmentById(document).subscribe(()=>{ }, error =>{ this.toastService.badRequest(); }); } else if(document['action'] == 'delete') { delete document.action this.attachmentsService.deleteEventAttachmentById(document.Id).subscribe( res=>{ }, error =>{ this.toastService.badRequest() }) } }) } async gravasAction() { await this.save(); if(this.eventProcess['activityInstanceName'] == 'Editar Evento') { this.reenviar(); } } async reenviar() { let body = { serialNumber: this.eventProcess.serialNumber, action: "Reenviar", dataFields: { ReviewUserComment: "", } } const loader = this.toastService.loading(); try { await this.processes.PostTaskAction(body).toPromise(); this.toastService._successMessage(); this.goToApproveEventList(); } catch (error) { this.toastService._badRequest(); } finally { loader.remove() } } goToApproveEventList() { this.closeEventToApprove.emit(); this.modalController.dismiss(); } dynamicSetIntervenient({taskParticipants, taskParticipantsCc}) { this.taskParticipants = removeDuplicate(taskParticipants) ; this.taskParticipantsCc = removeDuplicate(taskParticipantsCc) ; } async addParticipants() { //this.saveTemporaryData(); this.openAttendeesComponent.emit({ type: "intervenient" }); this.clearContact.emit(); } async addParticipantsCC() { this.openAttendeesComponent.emit({ type: "CC" }); this.clearContact.emit(); } saveTemporaryData() { this.getDatepickerData() window['temp.path:/shared/agenda/edit-event-to-approve.ts'] = { eventProcess: this.eventProcess } } restoreTemporaryData(): boolean { const restoredData = window['temp.path:/shared/agenda/edit-event-to-approve.ts'] if(JSON.stringify(restoredData) != "{}" && undefined != restoredData) { this.eventProcess = restoredData.eventProcess // restore dater for date and hours picker this.restoreDatepickerData() return true; } else { return false; } } async getAttachments() { let result: any = await this.attachmentsService.getAttachmentsById(this.InstanceId).toPromise(); result.forEach((e)=>{ e.action = false }) this.loadedAttachments = result // } deleteAttachment(attachment: Attachment, index) { this.loadedAttachments[index]['action'] = 'delete' } async getDoc() { const modal = await this.modalController.create({ component: SearchPage, cssClass: 'modal-width-100-width-background modal', componentProps: { type: 'AccoesPresidenciais & ArquivoDespachoElect', showSearchInput: true, select: true, } }); await modal.present(); modal.onDidDismiss().then( async (res)=>{ if(res){ const data: SearchList = res.data.selected; const DocumentToSave: any = { SourceTitle: data.Assunto, ParentId: this.InstanceId, Source: '1', SourceId: data.Id, ApplicationId: data.ApplicationType.toString(), Id: '', Link: '', SerialNumber: '', action: 'add', CreateDate: data.Data, Data: data.Data, Description: data.DocTypeDesc, SourceName: data.Assunto, Stakeholders: data.EntidadeOrganicaNome, }; this.loadedAttachments.push(DocumentToSave) // await this.attachmentsService.setEventAttachmentById(DocumentToSave).subscribe(()=>{ // this.getAttachments(); // }); } }); } restoreDatepickerData() { this.dateControlStart = new FormControl(moment(new Date(this.eventProcess.workflowInstanceDataFields.StartDate))); this.dateControlEnd = new FormControl(moment(new Date(this.eventProcess.workflowInstanceDataFields.EndDate))); } getDatepickerData() { this.eventProcess.workflowInstanceDataFields.StartDate = this.dateStart this.eventProcess.workflowInstanceDataFields.EndDate = this.dateEnd } }