Files
doneit-web/src/app/shared/agenda/edit-event/edit-event.page.ts
T
2024-05-29 15:43:37 +01:00

656 lines
18 KiB
TypeScript

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 { AttachmentsService } from 'src/app/services/attachments.service';
import { Attachment } from 'src/app/models/attachment.model';
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 { DomSanitizerService } from 'src/app/services/DomSanitizer.service';
import { AgendaDataRepositoryService } from 'src/app/services/Repositorys/Agenda/agenda-data-repository.service';
@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: Attachment[]=[];
recurringTypes = [];
selectedRecurringType: any;
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<any>();
@Output() openAttendeesComponent = new EventEmitter<any>();
@Output() closeComponent = new EventEmitter<any>();
@Output() setIntervenient = new EventEmitter<any>();
@Output() setIntervenientCC = new EventEmitter<any>();
@Output() clearPostEvent = new EventEmitter<any>();
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()
sesseionStora = SessionStore
CalendarNameOwnerName = ''
CalendarNamesOptions = []
allDayCheck: boolean = false;
constructor(
private modalController: ModalController,
private eventsService: EventsService,
public alertController: AlertController,
private attachmentsService: AttachmentsService,
public ThemeService: ThemeService,
private httpErrorHandle: HttpErrorHandle,
private contactsService: ContactsService,
private domSanitizeService: DomSanitizerService,
private agendaDataRepository: AgendaDataRepositoryService
) {
}
ngOnInit() {
console.log(this.postEvent)
this._postEvent = this.postEvent
this.allDayCheck = this.postEvent.IsAllDayEvent;
if(!this.restoreTemporaryData()) {
// 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;
this.getRecurrenceTypes();
setTimeout(() => {
this._postEvent.EventRecurrence.Type = this._postEvent.EventRecurrence.Type.toString();
}, 500);
this.CalendarNameOwnerName = this.eventsService.detectCalendarNameByCalendarId(this._postEvent.CalendarId)
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();
}
getRecurrenceTypes() {
this.eventsService.getRecurrenceTypes().subscribe(res=>{
this.recurringTypes = res;
});
}
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
}
onSelectedRecurringChanged(ev:any){
this.calculetedLastOccurrence(ev);
if(ev.length > 1){
this._postEvent.EventRecurrence.Type = ev.filter(data => data != '-1');
}
if(ev.length == 0){
this._postEvent.EventRecurrence.Type = "-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._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;
}
}
save_v2() {
this.injectValidation()
this.runValidation()
if (this.Form.invalid) {
return false
}
this.showLoader = true;
this.agendaDataRepository.updateEvent(this._postEvent.EventId, this._postEvent,this._postEvent.CalendarName,this.loadedEventAttachments);
this.showLoader = false;
this.httpErrorHandle.httpsSucessMessagge('Editar evento')
}
async save() {
this.injectValidation()
this.runValidation()
if(this.Form.invalid) {
return false
}
this._postEvent.Attendees = this.taskParticipants.concat(this.taskParticipantsCc);
this._postEvent.Subject = /* this.domSanitizeService.sanitizeInput( */this._postEvent.Subject/* ) */;
this._postEvent.Location = /* this.domSanitizeService.sanitizeInput( */this._postEvent.Location/* ) */;
this._postEvent.Body.Text = /* this.domSanitizeService.sanitizeInput( */this._postEvent.Body.Text/* ) */;
if(!this._postEvent.EventRecurrence.hasOwnProperty('Type')) {
this._postEvent.EventRecurrence.Type = '-1'
} else {
}
if(this._postEvent.EventRecurrence.Type == undefined) {
this._postEvent.EventRecurrence.Type = '-1'
}
this.showLoader = true;
try {
if(this.sesseionStora.user.Profile == 'MDGPR' || this.sesseionStora.user.Profile == 'PR') {
await this.eventsService.editEvent(this._postEvent, 2, 3, this._postEvent.CalendarId).toPromise()
if(this.initCalendarName != this._postEvent.CalendarName) {
let body = {
"EventId": this._postEvent.EventId,
"CalendarDestinationName": this._postEvent.CalendarName,
}
try {
await this.eventsService.changeAgenda(body).toPromise();
} catch (e) {}
}
this.showLoader = false;
this.httpErrorHandle.httpsSucessMessagge('Editar evento')
} else {
console.log(this._postEvent, 2, 3, this._postEvent.CalendarId)
await this.eventsService.editEvent(this._postEvent, 2, 3, this._postEvent.CalendarId).toPromise()
if(this.initCalendarName != this._postEvent.CalendarName) {
let body = {
"EventId": this._postEvent.EventId,
"CalendarDestinationName": this._postEvent.CalendarName,
}
try {
await this.eventsService.changeAgenda(body).toPromise();
} catch (e) {}
}
this.showLoader = false;
this.httpErrorHandle.httpsSucessMessagge('Editar evento')
}
} catch(error) {
this.showLoader = false
this.httpErrorHandle.httpStatusHandle(error)
}
this.clearPostEvent.emit();
this.deleteTemporaryData();
await this.saveDocument()
this.close();
}
async saveDocument() {
try {
for( let e of this.loadedEventAttachments) {
const id: any = e.Id
const remove = e['remove']
if ( id == 'add') {
//data.selected
const DocumentToSave = {
SourceTitle: e.SourceName,
ParentId: this._postEvent.EventId,
Source: '1',
SourceId: e.SourceId,
ApplicationId: e.ApplicationId.toString(),
Id: '0',
Link: '',
SerialNumber: '',
};
// await this.attachmentsService.setEventAttachmentById(DocumentToSave).toPromise();
} else if(remove) {
await this.attachmentsService.deleteEventAttachmentById(e.Id).toPromise()
}
}
} catch (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();
}
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'] = {}
}
async getAttachments(eventId: string){
if(this._postEvent.HasAttachments) {
let rest: any;
try {
rest = this.attachmentsService.getAttachmentsById(eventId).toPromise()
} catch (error) {
console.error('getAttchment', error)
}
this.loadedEventAttachments = rest;
}
}
deleteAttachment(attachmentID: string, index) {
const id: any = this.loadedEventAttachments[index].Id
if(id == 'add') {
this.loadedEventAttachments = this.loadedEventAttachments.filter((e,i)=> i!=index)
} else {
this.loadedEventAttachments[index]['remove'] = true
}
}
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,
}
});
modal.onDidDismiss().then( async (res) => {
if(res) {
const data = res.data;
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: '',
}
this.loadedEventAttachments.push(ApplicationIdDocumentToSave)
}
});
await modal.present();
}
changeAgenda() {
setTimeout(() => {
if(this.eventsService.calendarNamesType[this.CalendarNameOwnerName]?.['Oficial'] && this.eventsService.calendarNamesType[this.CalendarNameOwnerName]?.['Pessoal']) {
this.CalendarNamesOptions = ['Oficial', 'Pessoal']
} else if (this.eventsService.calendarNamesType[this.CalendarNameOwnerName]?.['Oficial']) {
this.CalendarNamesOptions = ['Oficial']
this._postEvent.CalendarName = 'Oficial'
} else if (this.eventsService.calendarNamesType[this.CalendarNameOwnerName]?.['Pessoal']) {
this.CalendarNamesOptions = ['Pessoal']
this._postEvent.CalendarName = 'Pessoal'
} else {
this.CalendarNamesOptions = ['Oficial', 'Pessoal']
}
}, 50)
}
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
}
}