Files
doneit-web/src/app/pages/agenda/new-event/new-event.page.ts
T
2022-07-14 16:35:42 +01:00

500 lines
13 KiB
TypeScript

import { Component, OnInit } from '@angular/core';
import { ModalController, NavParams } from '@ionic/angular';
import { EventAttachment } from 'src/app/models/attachment.model';
import { EventBody } from 'src/app/models/eventbody.model';
import { EventPerson } from 'src/app/models/eventperson.model';
import { SearchList } from 'src/app/models/search-document';
import { LoginUserRespose } from 'src/app/models/user.model';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { AuthService } from 'src/app/services/auth.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 { ThemePalette } from '@angular/material/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
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';
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-new-event',
templateUrl: './new-event.page.html',
styleUrls: ['./new-event.page.scss'],
providers: [
{ provide: NGX_MAT_DATE_FORMATS, useValue: CUSTOM_DATE_FORMATS },
]
})
export class NewEventPage implements OnInit {
// date picker
public date: any;
public disabled = false;
public showSpinners = true;
public showSeconds = false;
public touchUi = false;
public enableMeridian = false;
public stepHour = 1;
public stepMinute = 5;
public stepSecond = 5;
public color: ThemePalette = 'primary';
currentDate = new Date();
Form: FormGroup;
validateFrom = false
postEvent: Event;
eventBody: EventBody;
segment:string = "true";
profile:string;
eventAttendees: EventPerson[];
selectedSegment: string;
selectedDate: Date;
recurringTypes: any;
selectedRecurringType: any;
adding: "intervenient" | "CC";
taskParticipants: any = [];
taskParticipantsCc: any = [];
documents:SearchList[] = [];
loggeduser: LoginUserRespose;
members:any;
CalendarName;
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];
autoStartTime;
autoEndTime;
CalendarNamesOptions = ['Oficial', 'Pessoal']
constructor(
private modalController: ModalController,
private navParams: NavParams,
public eventService: EventsService,
private attachmentsService: AttachmentsService,
private toastService: ToastService,
userService: AuthService,
public ThemeService: ThemeService
) {
this.loggeduser = userService.ValidatedUser;
this.postEvent = new Event();
this.postEvent.EventRecurrence = {Type:'-1'};
this.eventBody = { BodyType : "1", Text : ""};
this.postEvent.Body = this.eventBody;
this.selectedSegment = this.navParams.get('segment');
this.selectedDate = this.navParams.get('eventSelectedDate');
this.taskParticipants = this.navParams.get('attendees');
}
ngOnInit() {
this.CalendarName = this.loggeduser.Profile;
this.selectedRecurringType = "-1";
this.getRecurrenceTypes();
if(this.selectedSegment != "Combinada"){
this.postEvent = {
EventId: '',
Subject: '',
Body: this.eventBody,
Location: '',
CalendarId: '',
CalendarName: 'Oficial',
StartDate: this.autoStartTime,
EndDate: this.autoEndTime,
EventType: 'Reunião',
Attendees: null,
IsMeeting: false,
IsRecurring: false,
AppointmentState: 0,
TimeZone: '',
Organizer: '',
Category: 'Reunião',
HasAttachments: false,
EventRecurrence: {Type:'-1',LastOccurrence:this.autoEndTime},
};
}
else{
this.postEvent = {
EventId: '',
Subject: '',
Body: this.eventBody,
Location: '',
CalendarId: '',
CalendarName: 'Oficial',
StartDate: this.autoStartTime,
EndDate: this.autoEndTime,
EventType: 'Reunião',
Attendees: null,
IsMeeting: false,
IsRecurring: false,
AppointmentState: 0,
TimeZone: '',
Organizer: '',
Category: 'Reunião',
HasAttachments: false,
EventRecurrence: {Type:'-1',LastOccurrence:this.autoEndTime},
};
}
window.onresize = (event) => {
if( window.innerWidth >= 1024){
this.modalController.dismiss();
}
};
}
close() {
this.modalController.dismiss();
}
getRecurrenceTypes() {
this.eventService.getRecurrenceTypes().subscribe( res => {
this.recurringTypes = res;
});
}
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;
if(new Date(this.postEvent.StartDate).getTime() > new Date(this.postEvent.EndDate).getTime()){
this.toastService._badRequest("A data de fim não pode ser inferior a data de início do evento")
}
}
get dateValid() {
if (window.innerWidth <= 800) {
return this.postEvent.StartDate < this.postEvent.EndDate? ['ok']: []
} else {
return ['ok']
}
}
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
]),
Date: new FormControl(new Date(this.postEvent.StartDate).getTime() <= new Date(this.postEvent.EndDate).getTime()? 'ok': null,[
Validators.required
]),
Categories: new FormControl(this.postEvent.Category, [
Validators.required
]),
participantes: new FormControl(this.taskParticipants, [
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
]),
})
}
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.documents.length >= 0) {
this.postEvent.HasAttachments = true;
}
if(this.selectedRecurringType != '-1') {
this.postEvent.EventRecurrence.Type = this.selectedRecurringType;
}
this.postEvent.Attendees = this.taskParticipants.concat(this.taskParticipantsCc);
let eventId: any;
const loader = this.toastService.loading()
try {
const CalendarId = this.selectedCalendarId()
if(this.loggeduser.Profile == 'MDGPR') {
eventId = await this.eventService.postEventGeneric(this.postEvent, this.postEvent.CalendarName, CalendarId).toPromise();
}
else if(this.loggeduser.Profile == 'PR') {
const CalendarId = this.selectedCalendarId()
eventId = await this.eventService.postEventGeneric(this.postEvent, this.postEvent.CalendarName, CalendarId).toPromise();
} else {
const CalendarId = this.selectedCalendarId()
eventId = await this.eventService.postEventGeneric(this.postEvent, this.postEvent.CalendarName, CalendarId).toPromise();
}
const DocumentToSave: EventAttachment[] = this.documents.map((e) => {
return {
SourceTitle: e.Assunto,
ParentId: eventId,
Source: '1',
SourceId: e.Id,
ApplicationId: e.ApplicationType.toString(),
Id: '',
Link: '',
SerialNumber: ''
};
});
await DocumentToSave.forEach( async (attachments, i) => {
try {
await this.attachmentsService.setEventAttachmentById(attachments).toPromise();
} catch(error) {
}
});
this.toastService._successMessage()
this.modalController.dismiss(this.postEvent);
} catch (error) {
this.toastService._badRequest()
} finally {
loader.remove()
}
}
selectedCalendarId () {
if (this.eventService.calendarNamesType[this.CalendarName]?.['Oficial'] && this.postEvent.CalendarName == 'Oficial') {
return this.eventService.calendarNamesType[this.CalendarName]['OficialId']
} else if (this.eventService.calendarNamesType[this.CalendarName]?.['Pessoal'] && this.postEvent.CalendarName == 'Pessoal') {
return this.eventService.calendarNamesType[this.CalendarName]['PessoalId']
} else {
return '11:11'
}
}
changeAgenda() {
setTimeout(() => {
if(this.eventService.calendarNamesType[this.CalendarName]?.['Oficial'] && this.eventService.calendarNamesType[this.CalendarName]?.['Pessoal']) {
this.CalendarNamesOptions = ['Oficial', 'Pessoal']
} else if (this.eventService.calendarNamesType[this.CalendarName]?.['Oficial']) {
this.CalendarNamesOptions = ['Oficial']
this.postEvent.CalendarName = 'Oficial'
} else if (this.eventService.calendarNamesType[this.CalendarName]?.['Pessoal']) {
this.CalendarNamesOptions = ['Pessoal']
this.postEvent.CalendarName = 'Pessoal'
} else {
this.CalendarNamesOptions = ['Oficial', 'Pessoal']
}
}, 50)
}
async openAttendees() {
const modal = await this.modalController.create({
component: AttendeesPageModal,
componentProps: {
adding: this.adding,
taskParticipants: this.taskParticipants,
taskParticipantsCc: this.taskParticipantsCc
},
cssClass: 'attendee modal modal-desktop',
backdropDismiss: false
});
await modal.present();
modal.onDidDismiss().then((data) => {
if(data) {
data = data['data'];
if(data) {
const newAttendees: EventPerson[] = data['taskParticipants'];
const newAttendeesCC: EventPerson[] = data['taskParticipantsCc'];
if(newAttendees.length) {
this.setIntervenient(newAttendees);
}
if(newAttendeesCC) {
this.setIntervenientCC(newAttendeesCC);
}
}
}
});
}
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();
}
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((res)=>{
if(res){
const data = res.data;
this.documents.push(data.selected);
}
});
}
removeAttachment(index: number){
this.documents = this.documents.filter( (e, i) => index != i);
}
}