Files
doneit-web/src/app/ui/agenda/component/new-event/new-event.page.ts
T
2024-10-22 14:31:04 +01:00

685 lines
18 KiB
TypeScript

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Event } from 'src/app/models/event.model';
import { ModalController } from '@ionic/angular';
import { removeDuplicate } from 'src/plugin/removeDuplicate.js'
import { SearchPage } from 'src/app/pages/search/search.page';
import { SearchList_v2 } from "src/app/models/search-document";
import { ToastService } from 'src/app/services/toast.service';
import { LoginUserRespose } from 'src/app/models/user.model';
import { DateAdapter } from '@angular/material/core';
import * as _moment from 'moment';
import * as _rollupMoment from 'moment';
import { FormControl } from '@angular/forms';
import { NgxMatDateFormats } from '@angular-material-components/datetime-picker';
import { ThemePalette } from '@angular/material/core';
import { FormGroup, Validators } from '@angular/forms';
import { NGX_MAT_DATE_FORMATS } from '@angular-material-components/datetime-picker';
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 { environment } from 'src/environments/environment';
import { Observable } from 'rxjs';
import { TaskService } from 'src/app/services/task.service'
import { ChangeProfileService } from 'src/app/services/change-profile.service';
import { AgendaDataRepositoryService } from 'src/app/module/agenda/data/repository/agenda-data-repository.service';
import { RoleIdService } from 'src/app/services/role-id.service'
import { TableSharedCalendar } from 'src/app/module/agenda/data/data-source/agenda-local-data-source.service';
import { TracingType, XTracerAsync } from 'src/app/services/monitoring/opentelemetry/tracer';
import { UserList } from 'src/app/models/entiry/agenda/contact';
import { AgendaService } from 'src/app/module/agenda/domain/agenda.service'
import { RoleId } from 'src/app/core/agenda/use-case/event-set-default-participants.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-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 {
public date: any;
public disabled = false;
public showSpinners = true;
public showSeconds = false;
public touchUi = false;
public enableMeridian = false;
public stepHour = 1;
public stepMinute = 15;
public stepSecond = 15;
public color: ThemePalette = 'primary';
selectedRecurringType: any;
loggedAttendDad: boolean = true;
mostrarModal = false;
@Input() attendees: []
@Input() profile: string;
@Input() roomId: string;
@Input() selectedSegment: string;
@Input() selectedDate: Date;
@Input() CalendarDate: Date;
@Input() taskParticipants: UserList = [];
@Input() taskParticipantsCc: any = [];
@Output() setIntervenient = new EventEmitter<any>();
@Output() setIntervenientCC = new EventEmitter<any>();
postEvent: Event;
@Output() onAddEvent = new EventEmitter<any>();
@Output() openAttendeesComponent = new EventEmitter<any>();
@Output() clearContact = new EventEmitter<any>();
@Output() GoBackEditOrAdd = new EventEmitter<any>();
@Output() cloneAllmobileComponent = new EventEmitter<any>();
@Output() backToChat = new EventEmitter<any>();
documents: SearchList_v2[] = [];
loggeduser: LoginUserRespose;
Form: FormGroup;
validateFrom = false;
autoStartTime;
autoEndTime;
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];
showLoader = false
CalendarName;
CalendarNameShow = true
CalendarNamesOptions = ['Oficial', 'Pessoal']
environment = environment
eventPersons: UserList;
contacts: UserList = [];
allDayCheck: boolean = false;
sharedCalendar: Observable<TableSharedCalendar[]>
selectedUserCalendar:any;
SessionStore = SessionStore
hasChangeCalendar = false
daysOfWeek = {
sun: false,
mon: false,
tues: false,
wed: false,
thurs: false,
fri: false,
sat: false,
};
constructor(
private modalController: ModalController,
private toastService: ToastService,
private dateAdapter: DateAdapter<any>,
public ThemeService: ThemeService,
private hhtpErrorHandle: HttpErrorHandle,
public TaskService: TaskService,
private changeProfileService: ChangeProfileService,
private agendaDataRepository: AgendaDataRepositoryService,
public RoleIdService: RoleIdService,
private AgendaService: AgendaService
) {
this.dateAdapter.setLocale('pt');
this.loggeduser = SessionStore.user;
this.postEvent = new Event();
this.sharedCalendar = this.agendaDataRepository.getShareCalendarItemsLiveWithOrder()
}
hasPrCalendar(data: TableSharedCalendar[]) {
for(const e of data) {
if(e.roleId == this.RoleIdService.PRES) {
return true
}
}
return false
}
async setCalendarByDefault(force) {
if (!this.selectedUserCalendar || force) {
const data = await this.agendaDataRepository.geCalendars()
const prObject = data.find(e => e?.roleId == RoleId.PRES)
if(prObject) {
this.selectedUserCalendar = prObject.wxUserId
} else {
this.selectedUserCalendar = SessionStore.user.UserId
}
this.changeAgenda()
}
}
ngOnInit() {
this.changeProfileService.registerCallback(() => {
this.initializeData()
})
// this.getRecurrenceTypes();
if (!this.restoreTemporaryData()) {
// clear
this.setCalendarByDefault(true)
this.postEvent.Body = { BodyType: "1", Text: "" };
this.initializeData()
if (this.postEvent.Attendees != null) {
this.postEvent.Attendees.forEach(e => {
if (e.IsRequired) {
this.taskParticipants.push(e as any);
} else {
this.taskParticipantsCc.push(e);
}
})
}
console.log('Attendes', this.taskParticipants)
this.taskParticipants = removeDuplicate(this.taskParticipants);
this.taskParticipantsCc = removeDuplicate(this.taskParticipantsCc);
this.setIntervenient.emit(this.taskParticipants);
this.setIntervenientCC.emit(this.taskParticipantsCc);
this.setDefaultTime();
this.fetchContacts("")
}
this.injectValidation();
this.changeAgenda()
}
initializeData() {
this.postEvent = {
EventId: '',
Subject: '',
Body: { BodyType: "1", Text: "" },
Location: '',
CalendarId: '',
CalendarName: 'Oficial',
StartDate: this.autoStartTime,
EndDate: this.autoEndTime,
EventType: 'Reunião',
Attendees: this.attendees || null,
IsMeeting: false,
IsRecurring: false,
AppointmentState: 0,
TimeZone: '',
Organizer: '',
Category: 'Meeting',
HasAttachments: false,
EventRecurrence: {
frequency: "never",
until: "",
Type: '',
daysOfWeek: []
},
}
}
setDefaultTime() {
this.postEvent.StartDate = this.roundTimeQuarterHour(this.CalendarDate);
this.postEvent.EndDate = this.roundTimeQuarterHourPlus15(this.postEvent.StartDate);
}
roundTimeQuarterHour(timeToReturn = new Date()): Date {
let date = new Date(timeToReturn) || new Date();
let newdate = new Date();
const minutes = newdate.getMinutes();
date.setHours(newdate.getHours())
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
}
roundTimeQuarterHour1(timeToReturn) {
let date: any = new Date(timeToReturn) || new Date();
const minutes = date.getMinutes();
date.setSeconds(0);
if ((minutes % 15) != 0) {
let a = (Math.floor(minutes / 15) + 1) * 15
date.setMinutes(a)
}
return date
}
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")
}
}
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),
Categories: new FormControl(this.postEvent.Category, [
Validators.required
]),
dateStart: new FormControl(this.postEvent.StartDate, [
Validators.required
]),
dateEnd: new FormControl(this.postEvent.EndDate, [
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).getTime() < new Date(this.postEvent.EndDate).getTime() ? 'ok' : null, [
Validators.required
]),
})
}
openFim() {
let input: any = document.querySelector('#new-fim')
if (input) {
input.click()
}
}
changeSegmentCalendar() {
this.hasChangeCalendar = true
}
async changeAgenda() {
this.CalendarNameShow = false
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']
}
}
}
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((res) => {
if (res) {
const data = res.data;
/* let newDocObject: SearchList_v2 = {
docId: parseInt(data.selected.Id),
sourceName: data.selected.Assunto,
description: "",
applicationId: data.selected.ApplicationType
} */
console.log('get doc', data)
this.documents.push(data.selected);
console.log('pushed')
}
});
await modal.present();
}
close() {
this.deleteTemporaryData();
this.clearContact.emit();
this.setIntervenient.emit([]);
this.setIntervenientCC.emit([]);
// chat exit
this.backToChat.emit({ roomId: this.roomId })
// agenda exit
this.cloneAllmobileComponent.emit({})
}
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;
}
}
@XTracerAsync({name:'desktop/create-event', bugPrint: true})
async save_v2(tracing?: TracingType) {
this.injectValidation()
this.runValidation()
if (this.Form.invalid) {
if (new Date(this.postEvent.StartDate).getTime() < new Date(this.postEvent.EndDate).getTime()) {
this.toastService._badRequest("Data de inicio menor que a data de fim")
}
return false
}
let i =0;
this.postEvent.EventRecurrence.daysOfWeek = []
for(const [key, value] of Object.entries(this.daysOfWeek)) {
if(value) {
if(!this.postEvent.EventRecurrence.daysOfWeek.includes(i)) {
this.postEvent.EventRecurrence.daysOfWeek.push(i);
}
}
i++
}
let loader = this.toastService.loading();
this.postEvent.Attendees = this.taskParticipants.concat(this.taskParticipantsCc) as any
this.postEvent.IsAllDayEvent = this.allDayCheck;
const calendar = await this.agendaDataRepository.getCalendarByUserId(this.selectedUserCalendar)
if(calendar.isOk()) {
const value = await this.agendaDataRepository.createEvent(this.postEvent, this.documents, calendar.value, tracing)
if(value.isOk()) {
console.log(value)
this.afterSave();
this.hhtpErrorHandle.httpsSucessMessagge('new event')
loader.remove();
tracing.setAttribute('outcome', 'success')
} else {
console.log('create event error: ', value.error)
tracing.setAttribute('outcome', 'failed')
loader.remove();
this.hhtpErrorHandle.httpStatusHandle(value.error.status)
}
} else {}
}
afterSave() {
this.deleteTemporaryData();
this.onAddEvent.emit(Object.assign(this.postEvent, {
roomId: this.roomId
}));
this.GoBackEditOrAdd.emit();
this.setIntervenient.emit([]);
this.setIntervenientCC.emit([]);
}
removeAttachment(index: number) {
this.documents = this.documents.filter((e, i) => index != i);
}
async addParticipants() {
this.saveTemporaryData();
this.openAttendeesComponent.emit({
type: "intervenient"
});
this.clearContact.emit();
this.mostrarModal = true;
}
async addParticipantsCc() {
this.saveTemporaryData();
this.openAttendeesComponent.emit({
type: "CC"
});
this.clearContact.emit();
}
saveTemporaryData() {
window['temp.path:/home/agenda/new-event.component.ts'] = {
postEvent: this.postEvent,
allDayCheck: this.allDayCheck,
CalendarName: this.CalendarName,
documents: this.documents,
selectedUserCalendar: this.selectedUserCalendar,
hasChangeCalendar: this.hasChangeCalendar,
daysOfWeek: this.daysOfWeek
}
}
/**
*
* @description o pipeline já esta a funcionar tuda vez que nos fazer push na branch master e test o pipeline executa os teste, mas agora os teste temos que melhora para testar a app em tudos os pontos
* o pipeline já está a funcionar toda vez que nos fazer um push na branch master ou teste o pipeline executa os testes, mas agora os testes temos que melhorar para testar a app em todos os pontos
*/
restoreTemporaryData(): boolean {
const restoredData = window['temp.path:/home/agenda/new-event.component.ts']
if (JSON.stringify(restoredData) != "{}" && undefined != restoredData) {
this.postEvent = restoredData.postEvent
this.allDayCheck = restoredData.allDayCheck
this.CalendarName = restoredData.CalendarName
this.documents = restoredData.documents
this.selectedUserCalendar = restoredData.selectedUserCalendar
this.hasChangeCalendar = restoredData.hasChangeCalendar
this.daysOfWeek = restoredData.daysOfWeek
// restore dater for date and hours picker
return true;
} else {
return false
}
}
deleteTemporaryData() {
window['temp.path:/home/agenda/new-event.component.ts'] = {}
}
async fetchContacts(filter: string) {
console.log(this.loggeduser.Profile)
//if(this.taskParticipants.length ==0) {
const result = await this.AgendaService.setDefaultParticipants()
if(result.isOk()) {
if(result.value) {
this.taskParticipants.push(result.value[0]);
this.setIntervenient.emit(result.value);
console.log('Attendes Email', result.value)
}
}
//}
}
onCheckboxChange(event: any) {
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
}
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
}
}
}