Files
doneit-web/src/app/home/home.page.ts
T
2024-02-28 09:51:49 +01:00

414 lines
12 KiB
TypeScript

import { Component, NgZone, OnInit } from '@angular/core';
import { Event } from '../models/event.model';
import { NotificationsService } from '../services/notifications.service';
import { AlertController, ModalController, Platform } from '@ionic/angular';
import { Router } from '@angular/router';
import { ToDayEventStorage } from '../store/to-day-event-storage.service';
import { TotalDocumentStore } from '../store/total-document.service';
import { ExpedienteGdStore } from '../store/expedientegd-store.service';
import { SessionStore } from '../store/session.service';
import { PermissionService } from '../services/permission.service';
import { BackgroundService } from 'src/app/services/background.service';
import { Storage } from '@ionic/storage';
import { EventsService } from 'src/app/services/events.service';
import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service';
import { ProcessesService } from 'src/app/services/processes.service';
import { RoleIdService } from 'src/app/services/role-id.service';
import { ActiveTabService } from 'src/app/services/active-tab.service';
import { Device } from '@capacitor/device';
import { RouteService } from 'src/app/services/route.service';
import { NetworkServiceService, ConnectionStatus } from 'src/app/services/network-service.service';
import { UserSession } from '../models/user.model';
import { PermissionList } from '../models/permission/permissionList';
import { SendIntent } from "send-intent";
// import { ChunkService } from "src/app/services/stream/chunk.service"
// import { StreamService } from "src/app/services/stream/stream.service"
import { Plugins } from '@capacitor/core';
import { NewActionPage } from '../pages/publications/new-action/new-action.page';
import { PublicationsPage } from '../pages/publications/publications.page';
// import { fetchData } from 'plugins/Echo';
import { Encoding, Filesystem, FilesystemDirectory } from '@capacitor/filesystem';
import { sendIntent } from 'src/app/services/shareIntent'
const { App } = Plugins;
@Component({
selector: 'app-home',
templateUrl: './home.page.html',
styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit {
eventsList: Event[];
prEventList: Event[];
mdEventList: Event[];
totalEvent = 0;
totalExpediente = 0;
profile: string;
toDayEventStorage = ToDayEventStorage
totalDocumentStore = TotalDocumentStore
expedienteGdStore = ExpedienteGdStore
adding: "intervenient" | "CC" = "intervenient";
mobileComponent = {
showAddNewEvent: false,
showEditEvent: false,
showEventDetails: false,
showEventList: false,
transparentEventList: false,
transparentEventToApprove: false,
showEventToApprove: false,
showAttendees: false,
showAttendeeModal: false
}
tabButton = {
home: false,
agenda: false,
gabinete: false,
actions: false,
chat: false,
}
eventToaprove: any = {
back: false,
serialNumber: "",
saveData: {}
}
selectedEvent: Event;
postEvent: any;
folderId: string;
status: string = "";
audioName: string = "";
public user: UserSession;
permissionList = new PermissionList();
SessionStore = SessionStore
intent: any;
constructor(
private router: Router,
public modalCtrl: AlertController,
private notificationsService: NotificationsService,
public platform: Platform,
public p: PermissionService,
private backgroundservice: BackgroundService,
private storage: Storage,
private eventservice: EventsService,
private processservice: ProcessesService,
public RouteService: RouteService,
private RochetChatConnectorService: RochetChatConnectorService,
private NetworkServiceService: NetworkServiceService,
public eventService: EventsService,
public ActiveTabService: ActiveTabService,
private RoleIdService: RoleIdService,
private modalController: ModalController,
private zone: NgZone
// private ChunkService: ChunkService,
// private StreamService: StreamService
) {
if (SessionStore.exist) {
this.user = SessionStore.user;
}
this.router.events.subscribe((val) => {
document.querySelectorAll('ion-modal').forEach((e: any) => e.remove())
document.querySelectorAll('popover-viewport').forEach((e: any) => e.remove())
document.querySelectorAll('.loading-blocker').forEach((e: any) => e.remove())
document.querySelectorAll('ion-popover').forEach((e: any) => e.remove())
});
window['platform'] = platform
window['inactivity/function'] = () => {
if (window.location.pathname != '/inactivity' && window.location.pathname != '/') {
document.querySelectorAll('ion-modal').forEach((e: any) => e.remove());
document.querySelectorAll('.popover-viewport').forEach((e: any) => e.remove());
document.querySelectorAll('.loading-blocker').forEach((e: any) => e.remove());
const pathname = window.location.pathname
SessionStore.setUrlBeforeInactivity(pathname)
if (this.platform.is('mobileweb')) {
window.location.pathname = '/inactivity'
} else {
window.location.pathname = '/'
}
}
}
sendIntent.setRouteService(this.router)
}
goto(url) {
this.router.navigateByUrl(url)
}
refreshing() { }
async checkSendIntentReceived() {
SendIntent.checkSendIntentReceived().then((result: any) => {
if (result) {
console.log('SendIntent received');
console.log(JSON.stringify(result));
}
if (result.url) {
window["sharedContent"] = result;
this.zone.run(() => this.router.navigateByUrl("/home/publications"));
}
}).catch(err => console.error(err));
}
ngOnInit() {
/* if (window["sharedintend"]) {
this.router.navigateByUrl("/home/publication");
} */
window["this.router"] = this.router
if (this.platform.is('ios'))
this.checkSendIntentReceived()
if ("serviceWorker" in navigator) {
navigator.serviceWorker.onmessage = (event) => {
console.log('Mensagem recebida do Service Worker:', event.data.data);
let object = {
notification: event.data
}
// Implemente a lógica para lidar com a mensagem recebida do Service Worker
if (event.data.notificationClicked) {
console.log('Notificação push do Firebase clicada em segundo plano!');
// Implemente ações adicionais conforme necessário
}
};
}
this.logDeviceInfo();
window.addEventListener('online', () => {
this.backgroundservice.online()
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
} else {
this.synchWhenOnline()
}
});
this.RochetChatConnectorService.registerCallback({
type: 'reConnect',
funx: async () => {
this.backgroundservice.online()
}
})
this.NetworkServiceService.onNetworkChange().subscribe((status) => {
if (status == ConnectionStatus.Online) {
this.backgroundservice.online()
}
})
window.addEventListener('offline', () => {
this.backgroundservice.offline()
});
this.updateList()
this.clearTabButtonSelection();
setTimeout(() => {
if (this.p.userPermission([this.p.permissionList.Gabinete.md_tasks]) && this.p.userPermission([this.p.permissionList.Gabinete.pr_tasks])) {
throw (SessionStore.user.FullName + 'cant have MD and PR authorization at same time');
}
if (this.p.userPermission([this.p.permissionList.Chat.access]) && !SessionStore.user?.ChatData?.data) {
throw ('Chat temporarily unavailable for ' + SessionStore.user.FullName + '. No ChatData');
}
if (this.p.userPermission([this.p.permissionList.Agenda.access]) && !this.eventService.hasAnyCalendar) {
throw ('User ' + SessionStore.user.FullName + 'has No calendar');
}
if (this.p.userPermission([this.p.permissionList.Gabinete.pr_tasks]) && SessionStore.user.RoleID != this.RoleIdService.PRES) {
throw ('User has PRES permission but not roleId');
}
if (!this.p.userPermission([this.p.permissionList.Gabinete.pr_tasks]) && SessionStore.user.RoleID == this.RoleIdService.PRES) {
throw (`User doesn't have PRES permission but has roleId`);
}
if (this.p.userPermission([this.p.permissionList.Gabinete.md_tasks]) && SessionStore.user.RoleID != this.RoleIdService.PV) {
throw ('User has vice president permission but not roleId');
}
if (!this.p.userPermission([this.p.permissionList.Gabinete.md_tasks]) && SessionStore.user.RoleID == this.RoleIdService.PV) {
throw (`User doesn't has vice president permission but has roleId`);
}
(() => {
document.addEventListener('click', (e: any) => {
const closest = e.target.closest(".mat-datepicker-content");
if (closest) {
e.preventDefault()
document.activeElement['blur']();
}
})
})()
}, 1000)
if (!this.platform.is('desktop')) {
App.addListener('appStateChange', ({ isActive }) => {
if (isActive) {
if (this.platform.is('ios')) {
this.checkSendIntentReceived();
} else if (this.platform.is('android')) {
sendIntent.setRouteService(this.router)
} else {
}
console.log('App is in the foreground');
/* this.checkSendIntentReceived() */
} else {
// The app is in the background.
console.log('App is in the background');
// You can perform actions specific to the background state here.
}
});
}
}
async imageToBase64(imageUri: string): Promise<string | null> {
try {
const result = await Filesystem.readFile({
path: imageUri,
directory: FilesystemDirectory.External, // Adjust the directory as needed
encoding: Encoding.UTF8,
});
// The result will contain the base64-encoded data
return result.data;
} catch (error) {
console.error('Error reading image:', error);
return null;
}
}
clearTabButtonSelection() {
this.tabButton.home = false;
this.tabButton.agenda = false;
this.tabButton.gabinete = false;
this.tabButton.actions = false;
this.tabButton.chat = false;
}
selectedTab(url?: string) {
this.clearTabButtonSelection();
if (url == '/home/events') {
this.tabButton.home = true;
}
else if (url == '/home/agenda') {
this.tabButton.agenda = true;
}
else if (url == '/home/gabinete-digital') {
this.tabButton.gabinete = true;
}
else if (url == '/home/publications') {
this.tabButton.actions = true;
}
else if (url == '/home/chat') {
this.tabButton.chat = true;
}
else {
this.clearTabButtonSelection();
}
}
logDeviceInfo = async () => {
const info = await Device.getInfo();
/* console.log('DEVICE INFO ',info); */
}
updateList() {
document.addEventListener('pause', function () {
});
document.addEventListener('resume', function () {
});
}
async synchWhenOnline() {
try {
await this.storage.get('eventEdit').then((req) => {
JSON.parse(req).forEach(element => {
this.eventservice.editEvent(element, 2, 3).subscribe((res) => {
this.storage.remove('eventEdit')
//this.sqliteservice.deleteeventsTable();
})
});
})
} catch (error) {
}
try {
await this.storage.get('eventDelete').then((req) => {
JSON.parse(req).forEach(element => {
this.eventservice.deleteEvent(element.eventid, element.eventDeleteType, element.calendarName).subscribe((res) => {
this.storage.remove('eventDelete')
})
});
})
} catch (error) {
}
try {
await this.storage.get('event-listRever').then((req) => {
JSON.parse(req).forEach(element => {
this.processservice.PostTaskAction(element).subscribe((res) => {
this.storage.remove('event-listRever')
})
});
})
} catch (error) {
}
// this.sqliteservice.deleteAllTables();
}
reloadComponent(self: boolean, urlToNavigateTo?: string) {
//skipLocationChange:true means dont update the url to / when navigating
console.log("Current route I am on:", this.router.url);
const url = self ? this.router.url : urlToNavigateTo;
this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
this.router.navigate([`/${url}`]).then(() => {
console.log(`After navigation I am on:${this.router.url}`)
})
})
}
}