Files
doneit-web/src/app/shared/agenda/edit-event/edit-event.page.ts
T
Peter Maquiran 55b1f488cb change word
2023-06-12 10:05:59 +01:00

512 lines
13 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';
@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;
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
constructor(
private modalController: ModalController,
private eventsService: EventsService,
public alertController: AlertController,
private attachmentsService: AttachmentsService,
public ThemeService: ThemeService,
private httpErrorHandle: HttpErrorHandle
) {}
ngOnInit() {
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, '');
}
}
}
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);
}
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( new Date(this.postEvent.StartDate).toLocaleString('pt') <= new Date(this.postEvent.EndDate).toLocaleString('pt')? 'ok': null,[
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;
}
}
async save() {
this.injectValidation()
this.runValidation()
if(this.Form.invalid) {
return false
}
this.postEvent.Attendees = this.taskParticipants.concat(this.taskParticipantsCc);
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).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 {
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() {
await this.loadedEventAttachments.forEach( async (e)=>{
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();
await this.getAttachments(this.postEvent.EventId);
} else if(remove) {
await this.attachmentsService.deleteEventAttachmentById(e.Id).toPromise()
}
})
}
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
}
}
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
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,
}
});
await modal.present();
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.Stakeholders | data.selected.EntidadeOrganicaNome,
ApplicationId: data.selected.ApplicationType.toString(),
CreateDate: data.selected.Data,
Id: 'add',
SourceTitle: data.selected.Assunto,
Source: '1',
Link: '',
SerialNumber: '',
}
this.loadedEventAttachments.push(ApplicationIdDocumentToSave)
}
});
}
}