Files
doneit-web/src/app/pages/agenda/edit-event/edit-event.page.ts
T
2024-03-02 12:38:30 +01:00

678 lines
18 KiB
TypeScript

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AlertController, ModalController, NavParams } from '@ionic/angular';
import { Attachment } from 'src/app/models/attachment.model';
import { EventBody } from 'src/app/models/eventbody.model';
import { EventPerson } from 'src/app/models/eventperson.model';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { EventsService } from 'src/app/services/events.service';
import { ToastService } from 'src/app/services/toast.service';
import { Event } from '../../../models/event.model';
import { AttendeesPageModal } from '../../events/attendees/attendees.page';
import { SearchPage } from '../../search/search.page';
import { ThemeService } from 'src/app/services/theme.service';
import { NgxMatDateFormats } from '@angular-material-components/datetime-picker';
import { NGX_MAT_DATE_FORMATS } from '@angular-material-components/datetime-picker';
import { SessionStore } from 'src/app/store/session.service';
import { HttpErrorHandle } from 'src/app/services/http-error-handle.service'
import { environment } from 'src/environments/environment';
import { ContactsService } from 'src/app/services/contacts.service';
import { DomSanitizerService } from 'src/app/services/DomSanitizer.service';
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',
templateUrl: './edit-event.page.html',
styleUrls: ['./edit-event.page.scss'],
providers: [
{ provide: NGX_MAT_DATE_FORMATS, useValue: CUSTOM_DATE_FORMATS },
]
})
export class EditEventPage implements OnInit {
Form: FormGroup;
validateFrom = false
postEvent: Event;
isRecurring: string;
isEventEdited: boolean;
loadedEvent: Event;
eventBody: EventBody;
segment: string = "true";
profile: string;
eventAttendees: EventPerson[];
selectedSegment: string;
selectedDate: Date;
initCalendarName: string;
caller: string;
recurringTypes: any;
selectedRecurringType: any;
CalendarNameOwnerName = ''
CalendarNamesOptions = []
public date: any;
public disabled = false;
public showSpinners = true;
public showSeconds = false;
public touchUi = false;
public enableMeridian = false;
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;
loadedEventAttachments: Attachment[] = [];
taskParticipants: any = [];
taskParticipantsCc: any = [];
adding: "intervenient" | "CC" = "intervenient";
showAttendees = 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];
sesseionStora = SessionStore
environment = environment
allDayCheck: boolean = false;
constructor(
private modalController: ModalController,
private navParams: NavParams,
public eventsService: EventsService,
public alertController: AlertController,
private attachmentsService: AttachmentsService,
private toastService: ToastService,
private router: Router,
public ThemeService: ThemeService,
private httpErrorHandle: HttpErrorHandle,
private contactsService: ContactsService,
private domSanitazerService: DomSanitizerService
) {
/* this.postEvent = new Event(); */
this.isEventEdited = false;
/* this.postEvent.EventRecurrence = { Type:'-1', LastOccurrence:''}; */
this.postEvent = this.navParams.get('event');
this.postEvent.StartDate = new Date(this.ajustMinuts(this.postEvent.StartDate))
this.postEvent.EndDate = new Date(this.ajustMinuts(this.postEvent.EndDate))
this.caller = this.navParams.get('caller');
this.initCalendarName = this.postEvent.CalendarName;
this.allDayCheck = this.postEvent.IsAllDayEvent;
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
}
}
if (this.postEvent) {
if (this.postEvent.Body) {
if (typeof (this.postEvent.Body.Text) == 'string') {
this.postEvent.Body.Text = this.postEvent.Body.Text.replace(/<[^>]+>/g, '');
}
}
}
if (this.postEvent.Attendees == null) {
this.taskParticipants = []
} else {
this.postEvent.Attendees.forEach(e => {
if (e.IsRequired) {
this.taskParticipants.push(e);
} else {
this.taskParticipantsCc.push(e);
}
})
}
if (this.postEvent.IsRecurring == false) {
this.isRecurring = "Não se repete";
}
else {
this.isRecurring = "Repete";
}
this.getAttachments(this.postEvent.EventId);
this.CalendarNameOwnerName = this.eventsService.detectCalendarNameByCalendarId(this.postEvent.CalendarId)
this.changeAgenda()
}
ngOnInit() {
window.onresize = (event) => {
// if not mobile remove all component
if (window.innerWidth >= 1024) {
this.modalController.dismiss();
}
}
if (window.innerWidth > 800) {
this.showAttendees = true;
}
this.getRecurrenceTypes();
setTimeout(() => {
this.selectedRecurringType = this.postEvent.EventRecurrence.Type.toString();
}, 500);
}
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.modalController.dismiss();
}
goBack() {
this.router.navigate(['/home', this.caller]);
}
getRecurrenceTypes() {
this.eventsService.getRecurrenceTypes().subscribe(res => {
this.recurringTypes = res;
});
}
roundTimeQuarterHour(timeToReturn = new Date()) {
let date = timeToReturn || 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.selectedRecurringType = ev.filter(data => data != '-1');
}
if (ev.length == 0) {
this.selectedRecurringType = "-1";
}
}
calculetedLastOccurrence(type: number) {
// console.log(type);
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;
}
}
runValidation() {
this.validateFrom = true
}
injectValidation() {
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, [
Validators.required
]),
Categories: new FormControl(this.postEvent.Category, [
Validators.required
]),
IsRecurring: new FormControl(this.postEvent.IsRecurring, [
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
]),
Date: new FormControl(new Date(this.postEvent.StartDate).getTime() <= new Date(this.postEvent.EndDate).getTime() ? 'ok' : null, [
Validators.required
]),
participantes: new FormControl(this.taskParticipants, [
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()
}
}
async save() {
this.injectValidation()
this.runValidation()
if (this.Form.invalid) return false;
if (this.selectedRecurringType != '-1') {
this.postEvent.EventRecurrence.Type = this.selectedRecurringType;
}
this.postEvent.Attendees = this.taskParticipants.concat(this.taskParticipantsCc)
this.postEvent.Subject = /* this.domSanitazerService.sanitizeInput( */this.postEvent.Subject/* ) */;
this.postEvent.Location = /* this.domSanitazerService.sanitizeInput( */this.postEvent.Location/* ) */;
this.postEvent.Body.Text = /* this.domSanitazerService.sanitizeInput( */this.postEvent.Body.Text/* ) */;
this.postEvent.EventRecurrence.Type = this.selectedRecurringType;
if (this.sesseionStora.user.Profile == 'MDGPR' || this.sesseionStora.user.Profile == 'PR') {
this.eventsService.editEvent(this.postEvent, 2, 3).subscribe(async () => {
if (window['reloadCalendar']) {
window['reloadCalendar']()
}
if (this.initCalendarName != this.postEvent.CalendarName) {
let body = {
"EventId": this.postEvent.EventId,
"CalendarDestinationName": this.postEvent.CalendarName,
}
try {
await this.eventsService.changeAgenda(body).toPromise();
} catch (error) { }
finally {
}
}
this.httpErrorHandle.httpsSucessMessagge('Editar evento')
}, error => {
this.httpErrorHandle.httpStatusHandle(error)
});
} else {
this.eventsService.editEvent(this.postEvent, 2, 3, this.postEvent.CalendarId).subscribe(async () => {
if (window['reloadCalendar']) {
window['reloadCalendar']()
}
if (this.initCalendarName != this.postEvent.CalendarName) {
let body = {
"EventId": this.postEvent.EventId,
"CalendarDestinationName": this.postEvent.CalendarName,
}
try {
await this.eventsService.changeAgenda(body).toPromise();
} catch (error) { }
finally {
}
}
this.httpErrorHandle.httpsSucessMessagge('Editar evento')
}, error => {
this.httpErrorHandle.httpStatusHandle(error)
});
}
this.isEventEdited = true;
await this.saveDocument()
this.goBack();
}
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) {
} finally {
}
this.modalController.dismiss({
isEventEdited: this.isEventEdited,
postEvent: this.postEvent
});
}
async openAttendees() {
if (window.innerWidth > 801) {
this.showAttendees = true;
}
else {
const modal = await this.modalController.create({
component: AttendeesPageModal,
componentProps: {
adding: this.adding,
taskParticipants: this.taskParticipants,
taskParticipantsCc: this.taskParticipantsCc
},
cssClass: 'modal attendee modal-desktop',
backdropDismiss: false
});
await modal.present();
modal.onDidDismiss().then((data) => {
if (data) {
data = data['data'];
const newAttendees: EventPerson[] = data['taskParticipants'];
const newAttendeesCC: EventPerson[] = data['taskParticipantsCc'];
if (newAttendees.length) {
this.setIntervenient(newAttendees);
} else {
this.setIntervenient([]);
}
if (newAttendeesCC) {
this.setIntervenientCC(newAttendeesCC);
} else {
this.setIntervenientCC([]);
}
}
});
}
}
setIntervenient(data) {
this.taskParticipants = data;
this.postEvent.Attendees = data;
}
setIntervenientCC(data) {
this.taskParticipantsCc = data;
}
addParticipants() {
this.adding = 'intervenient'
this.openAttendees();
}
addParticipantsCC() {
this.adding = 'CC';
this.openAttendees();
}
dynamicSetIntervenient({ taskParticipants, taskParticipantsCc }) {
this.taskParticipants = taskParticipants;
this.taskParticipantsCc = taskParticipantsCc;
}
getAttachments(eventId: string) {
if (this.postEvent.HasAttachments) {
this.attachmentsService.getAttachmentsById(eventId).subscribe(res => {
this.loadedEventAttachments = res;
}, ((erro) => {
console.error('editgetAttchament', erro)
}));
}
}
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: false,
ApplicationId: data.selected.ApplicationType.toString(),
CreateDate: false,
// needed to attach this document
Id: 'add',
SourceTitle: data.selected.Assunto,
Source: '1',
Link: '',
SerialNumber: '',
}
this.loadedEventAttachments.push(ApplicationIdDocumentToSave)
this.postEvent.Attachments = this.loadedEventAttachments;
}
})
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)
}
ajustMinuts(string) {
var partes = string.split(' ');
var horaMinuto = partes[1].split(':');
if (horaMinuto[1] === '59') {
horaMinuto[1] = '00';
var novaString = partes[0] + ' ' + horaMinuto.join(':');
return novaString;
}
return string;
}
onCheckboxChange(event: any) {
if (this.allDayCheck) {
this.postEvent.IsAllDayEvent = this.allDayCheck;
this.postEvent.StartDate = this.setAlldayTime(this.postEvent.StartDate)
console.log('Recurso ativado!!');
} else {
this.postEvent.IsAllDayEvent = this.allDayCheck;
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
}
}