import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core'; import { ModalController } from '@ionic/angular'; import { EventBody } from 'src/app/models/eventbody.model'; import { EventPerson } from 'src/app/models/eventperson.model'; import { EventsService } from 'src/app/services/events.service'; import { Event } from 'src/app/models/event.model'; import { AlertController } from '@ionic/angular'; import { removeDuplicate } from 'src/plugin/removeDuplicate.js' import { SearchPage } from 'src/app/pages/search/search.page'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { ParticipantsPipe } from 'src/app/pipes/participants.pipe'; import { ThemeService } from 'src/app/services/theme.service' import { SessionStore } from 'src/app/store/session.service'; import { HttpErrorHandle } from 'src/app/services/http-error-handle.service'; import { ContactsService } from 'src/app/services/contacts.service' import { AgendaDataRepositoryService } from 'src/app/module/agenda/data/repository/agenda-data-repository.service'; import { SearchList_v2 } from 'src/app/models/search-document'; import { Utils } from 'src/app/module/agenda/utils'; import { Observable } from 'rxjs'; import { TableSharedCalendar } from 'src/app/module/agenda/data/data-source/agenda-local-data-source.service'; import { RoleIdService } from 'src/app/services/role-id.service' import { XTracerAsync, TracingType } from 'src/app/services/monitoring/opentelemetry/tracer'; import { AttendeesLIstChangeDetector } from 'src/app/module/agenda/data/async/change/attendeesLIstChangeDetector'; import { EventRecurrenceComponentReturn, EventRecurrencePage } from 'src/app/modals/event-recurrence/event-recurrence.page'; @Component({ selector: 'app-edit-event', templateUrl: './edit-event.page.html', styleUrls: ['./edit-event.page.scss'], }) export class EditEventPage implements OnInit { stEvent: Event; isRecurring: string; isEventEdited: boolean; loadedEvent: Event; initCalendarName: string; eventBody: EventBody; segment: string = "true"; eventAttendees: EventPerson[]; // minDate: string; loadedEventAttachments: any[] = []; selectedRecurringType: any; deletedAttachmentsList = []; public date: any; public disabled = false; public showSpinners = true; public showSeconds = false; public touchUi = false; public enableMeridian = false; public minDate = new Date().toISOString().slice(0, 10) public endMinDate = new Date(new Date().getTime() + 15 * 60000).toISOString().slice(0, 10) public maxDate: any; public stepHour = 1; public stepMinute = 15; public stepSecond = 15; Form: FormGroup; validateFrom = false @Input() taskParticipants: EventPerson[]; @Input() taskParticipantsCc: EventPerson[]; @Input() profile: string; @Input() selectedSegment: string; @Input() postEvent: Event; @Output() clearContact = new EventEmitter(); @Output() openAttendeesComponent = new EventEmitter(); @Output() closeComponent = new EventEmitter(); @Output() setIntervenient = new EventEmitter(); @Output() setIntervenientCC = new EventEmitter(); @Output() clearPostEvent = new EventEmitter(); showLoader = false @ViewChild('picker') picker: any; @ViewChild('fim') fim: any; @ViewChild('inicio') inicio: any; @ViewChild('picker1') picker1: any; @Input() _postEvent: Event; public options = [ { value: true, label: 'True' }, { value: false, label: 'False' } ]; public listColors = ['primary', 'accent', 'warn']; public stepHours = [1, 2, 3, 4, 5]; public stepMinutes = [1, 5, 10, 15, 20, 25]; public stepSeconds = [1, 5, 10, 15, 20, 25]; private participantsPipe = new ParticipantsPipe() SessionStore= SessionStore allDayCheck: boolean = false; addedAttachmentsList = []; sharedCalendar: Observable hasChangeCalendar = false selectedUserCalendar:any; CalendarNamesOptions = ['Oficial', 'Pessoal'] dateDifference = 0 editAllEvent = false constructor( private modalController: ModalController, private eventsService: EventsService, public alertController: AlertController, public ThemeService: ThemeService, private httpErrorHandle: HttpErrorHandle, private contactsService: ContactsService, private agendaDataRepository: AgendaDataRepositoryService, private utils: Utils, public RoleIdService: RoleIdService, ) { this.sharedCalendar = this.agendaDataRepository.getShareCalendarItemsLiveWithOrder() } hasPrCalendar(data: TableSharedCalendar[]) { for(const e of data) { if(e.roleId == this.RoleIdService.PRES) { return true } } return false } changeSegmentCalendar() { this.hasChangeCalendar = true } ngOnInit() { this.selectedUserCalendar = this.postEvent.owner.wxUserId this.loadedEventAttachments = this.postEvent.Attachments this._postEvent = this.postEvent this._postEvent.Category = this.setEventType(this._postEvent.Category) if (!this._postEvent.IsRecurring) { this._postEvent.EventRecurrence.frequency = 'never'; } else { this._postEvent.EventRecurrence.frequency = this.utils.recurenceTypeSeleted(this.postEvent.EventRecurrence.frequency) } this.allDayCheck = this.postEvent.IsAllDayEvent; if (!this.restoreTemporaryData()) { this.validationEditAllEvent() // clear if (this._postEvent) { if (this._postEvent.Body) { if (typeof (this._postEvent.Body.Text) == 'string') { this._postEvent.Body.Text = this._postEvent.Body.Text.replace(/<[^>]+>/g, ''); } } } for (const index in this._postEvent.Attendees) { const user = this._postEvent.Attendees[index] const userData = this.contactsService.constacts.find(e => user.EmailAddress == e.EmailAddress) if (userData) { this._postEvent.Attendees[index].UserType = userData.UserType } else { console.log('user not set') } } if (this._postEvent.Attendees != null) { const result = this.participantsPipe.transform(this._postEvent.Attendees) this.taskParticipants = result.taskParticipants this.taskParticipantsCc = result.taskParticipantsCc this.taskParticipants = removeDuplicate(this.taskParticipants); this.taskParticipantsCc = removeDuplicate(this.taskParticipantsCc); this.setIntervenient.emit(this.taskParticipants); this.setIntervenientCC.emit(this.taskParticipantsCc); } } this.initCalendarName = this._postEvent.CalendarName; setTimeout(() => { this._postEvent.EventRecurrence.Type = this._postEvent.EventRecurrence.Type.toString(); }, 500); this.changeAgenda() } ngOnDestroy() { clearInterval(this.myInterval) } myInterval = setInterval(() => { document.querySelectorAll('.ngx-mat-timepicker input').forEach((e: any) => { if (e) { e.disabled = true; } }) }, 1000); ngOnChanges(changes: any): void { this.loadedEventAttachments = this._postEvent?.Attachments } close() { this.closeComponent.emit(); this.setIntervenient.emit([]); this.setIntervenientCC.emit([]); this.clearContact.emit(); this.deleteTemporaryData(); } runValidation() { this.validateFrom = true } injectValidation() { if (typeof (this._postEvent.EventRecurrence.Type) == 'number') { const str: any = this._postEvent.EventRecurrence.Type.toString() this._postEvent.EventRecurrence.Type = str } this.Form = new FormGroup({ Subject: new FormControl(this._postEvent.Subject, [ Validators.required, // Validators.minLength(4) ]), Location: new FormControl(this._postEvent.Location, [ Validators.required, ]), CalendarName: new FormControl(this._postEvent.CalendarName), Categories: new FormControl(this._postEvent.Category, [ Validators.required ]), dateOccurrence: new FormControl(this._postEvent.EventRecurrence.Type.toString() == '-1' ? ['ok'] : this._postEvent.EventRecurrence.LastOccurrence && new Date(this._postEvent.EventRecurrence.LastOccurrence).getTime() > new Date(this._postEvent.EndDate).getTime() ? 'ok' : null, [ Validators.required ]), participantes: new FormControl(this.taskParticipants, [ // Validators.required ]), Date: new FormControl(true, [ Validators.required ]), }) } openInicio() { let input: any = document.querySelector('#new-inicio') if (input) { input.click() } } openFim() { let input: any = document.querySelector('#new-fim') if (input) { input.click() } } openLastOccurrence() { let input: any = document.querySelector('#last-occurrence') if (input) { input.click() } } roundTimeQuarterHour() { let date = new Date(); const minutes = date.getMinutes(); date.setSeconds(0); if (minutes % 15 != 0) { if (minutes > 45) { date.setMinutes(60) } else if (minutes > 30) { date.setMinutes(45) } else if (minutes > 15) { date.setMinutes(30) } else if (minutes > 0) { date.setMinutes(15) } } return date } roundTimeQuarterHourPlus15(date: Date) { const _date = new Date(date); const minutes = _date.getMinutes(); _date.setMinutes(minutes + 15) return _date } 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._postEvent.EndDate); if (opcao == true) { time.setDate(time.getDate() + valor); this._postEvent.EventRecurrence.LastOccurrence = time; } else { time = new Date( time.getFullYear() + valor, time.getMonth(), time.getDate(), time.getHours(), time.getMinutes() ); this._postEvent.EventRecurrence.LastOccurrence = time; } } async validationEditAllEvent() { if (this.postEvent.IsRecurring ) { const modal = await this.modalController.create({ component: EventRecurrencePage, componentProps: {}, cssClass: 'event-recurrence-modal', }); modal.onDidDismiss().then((res) => { const data: EventRecurrenceComponentReturn = res.data if(data =='EditAll') { this.editAllEvent = true } else if (data == 'EditOne') { this.editAllEvent = false } else if(data == 'Cancel') { this.close() } else { this.close() } }); await modal.present(); } } @XTracerAsync({name:'desktop/edit-event', bugPrint: true, daley: 4000}) async save_v2(tracing?: TracingType) { this.injectValidation() this.runValidation() if (this.Form.invalid) { return false } const serverCurrentList = this._postEvent.Attendees this._postEvent.Attendees = this.taskParticipants.concat(this.taskParticipantsCc); try { const calendar = await this.agendaDataRepository.getCalendarByUserId(this.selectedUserCalendar) if(calendar.isOk()) { this.showLoader = true; const value = await this.agendaDataRepository.updateEvent(this._postEvent.EventId, this._postEvent, this.editAllEvent, calendar.value, tracing) if(value.isOk()) { console.log(value.value) this.httpErrorHandle.httpsSucessMessagge('Editar evento') this.clearPostEvent.emit(); this.deleteTemporaryData(); this.showLoader = false; tracing } else { console.log('edit event error: ', value.error) tracing.setAttribute('outcome', 'failed') } const { insert, remove } = AttendeesLIstChangeDetector(serverCurrentList as any, this._postEvent.Attendees as any) console.log({ insert, remove }); if(insert.length >= 1) { try { await this.agendaDataRepository.addEventAttendee(this._postEvent.EventId, insert, tracing).toPromise() } catch (error) { tracing.setAttribute('failed.attendees', 'true') console.log('add Attendee error: ', error) } // let a = this.agendaDataRepository.addEventAttendee(this._postEvent.EventId, insert, tracing).subscribe((value) => { // console.log(value) // }, ((error) => { // tracing.setAttribute('failed.attendees', 'true') // console.log('add Attendee error: ', error) // })); } if(remove.length >= 1) { try { await this.agendaDataRepository.removeEventAttendee(this._postEvent.EventId, remove).toPromise() } catch (error) { tracing.setAttribute('failed.attendees', 'true') console.log('add Attendee error: ', error) } // this.agendaDataRepository.removeEventAttendee(this._postEvent.EventId, remove).subscribe((value) => { // console.log(value) // }, ((error) => { // tracing.setAttribute('failed.attendees', 'true') // console.log('add Attendee error: ', error) // })); } if (this.addedAttachmentsList.length >= 1) { try { await this.agendaDataRepository.addEventAttachment(this._postEvent.EventId, this.loadedEventAttachments, tracing).toPromise() } catch (error) { this.showLoader = false tracing.setAttribute('failed.add.attachment', 'true') console.log('add attachment error: ', error) } // this.agendaDataRepository.addEventAttachment(this._postEvent.EventId, this.loadedEventAttachments, tracing).subscribe((value) => { // console.log(value) // }, ((error) => { // this.showLoader = false // tracing.setAttribute('failed.add.attachment', 'true') // console.log('add attachment error: ', error) // })); } if (this.deletedAttachmentsList.length >= 1) { try { await this.agendaDataRepository.removeEventAttachment(this._postEvent.EventId, { attachments: this.deletedAttachmentsList }).toPromise() } catch (error) { this.showLoader = false console.log('remove attachment error: ', error) } // this.agendaDataRepository.removeEventAttachment(this._postEvent.EventId, { attachments: this.deletedAttachmentsList }).subscribe((value) => { // console.log(value) // }, ((error) => { // this.showLoader = false // console.log('remove attachment error: ', error) // })); } this.close(); } else { console.log('this.selectedUserCalendar', this.selectedUserCalendar) console.log(calendar.error) } } catch (error) { this.httpErrorHandle.httpStatusHandle(error) console.log('edit: ', error) } } async addParticipants() { this.saveTemporaryData(); this.openAttendeesComponent.emit({ type: "intervenient" }); this.clearContact.emit(); } async addParticipantsCc() { this.saveTemporaryData(); this.openAttendeesComponent.emit({ type: "CC" }); this.clearContact.emit(); } onDateChange(e) { const cloneDateStartDate = new Date(this._postEvent.StartDate); const cloneDateEndDate = new Date(this._postEvent.EndDate); if(cloneDateStartDate.getTime() >= cloneDateEndDate.getTime()) { cloneDateStartDate.setHours(cloneDateStartDate.getHours() + 1); this._postEvent.EndDate = cloneDateStartDate } } saveTemporaryData() { window['temp.path:/home/agenda/edit-event.component.ts'] = { postEvent: this._postEvent, eventBody: this.eventBody, segment: this.segment, loadedEventAttachments: this.loadedEventAttachments, } } restoreTemporaryData(): boolean { const restoredData = window['temp.path:/home/agenda/edit-event.component.ts'] if (JSON.stringify(restoredData) != "{}" && undefined != restoredData) { this._postEvent = restoredData.postEvent this.eventBody = restoredData.eventBody this.segment = restoredData.segment this.loadedEventAttachments = restoredData.loadedEventAttachments return true; } else { return false; } } deleteTemporaryData() { window['temp.path:/home/agenda/edit-event.component.ts'] = {} } deleteAttachment(attachmentID: string, index) { const indexToRemove = index; // Assuming you already know the index you want to remove const DocumentId: any = this.loadedEventAttachments[index].Id if (indexToRemove > -1 && indexToRemove < this.loadedEventAttachments.length) { this.loadedEventAttachments.splice(indexToRemove, 1); } this.deletedAttachmentsList.push(DocumentId) } async getDoc() { const modal = await this.modalController.create({ component: SearchPage, cssClass: 'modal-width-100-width-background modal', componentProps: { type: 'AccoesPresidenciais & ArquivoDespachoElect', eventAgenda: true, showSearchInput: true, select: true, } }); modal.onDidDismiss().then(async (res) => { if (res) { const data = res.data; console.log('Get Doc', data.selected) /* const ApplicationIdDocumentToSave: any = { SourceName: data.selected.Assunto, ParentId: this._postEvent.EventId, SourceId: data.selected.Id, Stakeholders: data.selected.EntidadeOrganicaNome | data.selected.Stakeholders, ApplicationId: data.selected.ApplicationType.toString(), CreateDate: data.selected.Data, Id: 'add', SourceTitle: data.selected.Assunto, Source: '1', Link: '', SerialNumber: '', }*/ console.log({data}) let newDocObject: SearchList_v2 & {ApplicationId: any} = { docId: data.selected.docId, sourceName: data.selected.sourceName, description: data.selected.description, applicationId: data.selected.applicationId, classificator: data.selected.classificator, dateEntry: data.selected.dateEntry, docNumber: data.selected.docNumber, subject: data.selected.subject, userId: data.selected.userId, ApplicationId: data.selected.applicationId } this.loadedEventAttachments.push(data.selected) this.addedAttachmentsList.push(data.selected) } }); await modal.present(); } async changeAgenda() { const result = await this.agendaDataRepository.geCalendars() const selectedCalendar = result.find(e => e.wxUserId == this.selectedUserCalendar) if(selectedCalendar) { if(selectedCalendar.shareType == 1) { this.CalendarNamesOptions = ['Oficial'] } else if(selectedCalendar.shareType == 2) { this.CalendarNamesOptions = ['Pessoal'] } else if (selectedCalendar.shareType == 3) { this.CalendarNamesOptions = ['Oficial', 'Pessoal'] } } } onCheckboxChange(event: any) { console.log(this.postEvent.CalendarId) if (this.allDayCheck) { this.postEvent.IsAllDayEvent = this.allDayCheck; this.postEvent.StartDate = this.setAlldayTime(this.postEvent.StartDate) this.postEvent.EndDate = this.setAlldayTimeEndDate(this.postEvent.EndDate) console.log('Recurso ativado!!'); } else { this.postEvent.IsAllDayEvent = this.allDayCheck; this.postEvent.EndDate = this.setAlldayTimeEndDateNotAlday(this.postEvent.EndDate) console.log('Recurso desativado'); } } setAlldayTime(timeToReturn) { let date: any = new Date(timeToReturn) || new Date(); let newdate = new Date(); date.setHours(0) date.setMinutes(0) date.setSeconds(0); return date } setAlldayTimeEndDate(timeToReturn) { let date: any = new Date(timeToReturn) || new Date(); let newdate = new Date(); date.setHours(23) date.setMinutes(59) date.setSeconds(0); return date } setAlldayTimeEndDateNotAlday(timeToReturn) { let date: any = new Date(timeToReturn) || new Date(); let newdate = new Date(); date.setHours(23) date.setMinutes(0) date.setSeconds(0); return date } setEventType(eventType) { if(typeof eventType == 'number') { var selectedEventType = { 1: 'Meeting', 2: 'Travel', 3: 'Conference', 4: 'Encontro' } return selectedEventType[eventType]; } else { return this._postEvent.Category } } }