create event from gabinete

This commit is contained in:
Peter Maquiran
2024-07-04 16:33:45 +01:00
parent 0e12b5de5e
commit 06417ead0f
22 changed files with 881 additions and 311 deletions
@@ -24,7 +24,11 @@ import { EventUpdateInputDTOSchema } from './model/eventUpdateInputDtO';
import { AttachInputDTOSchema } from './model/addAttachmentDTOInput';
import { EventListDataOutputDTOSchema } from './model/eventListDTOOutput';
import { EventSearchMapper } from './mapper/EventSearchMapper';
import { select, Store } from '@ngrx/store';
import { CalendarState, pushEvent, removeRangeForCalendar, selectEventsInRange } from './agenda-memory-source.service';
import { NativeNotificationService } from 'src/app/services/native-notification.service';
import { ListBoxService } from 'src/app/services/agenda/list-box.service';
import { EventListStore } from 'src/app/models/agenda/AgendaEventList';
@Injectable({
providedIn: 'root'
})
@@ -33,7 +37,11 @@ export class AgendaDataRepositoryService {
constructor(
private agendaDataService: AgendaDataService,
private utils: Utils,
private agendaLocalDataSourceService: AgendaLocalDataSourceService
private agendaLocalDataSourceService: AgendaLocalDataSourceService,
private memoryStore: Store<CalendarState>,
private NativeNotificationService: NativeNotificationService,
public listBoxService: ListBoxService,
) { }
createOwnCalendar(): SharedCalendarListItemOutputDTO {
@@ -122,7 +130,47 @@ export class AgendaDataRepositoryService {
const result = await this.agendaDataService.getEvents(userId, startDate, endDate, status, category, type).pipe(
map((response) => {
APINODReturn(EventListDataOutputDTOSchema, response, 'get/Events', tracing)
return ListEventMapper.toDomain(response, calendarOwnerName, userId)
let profile;
if (SessionStore.user.Profile == 'PR') {
profile = "pr"
} else if (userId == SessionStore.user.UserId as any) {
profile = 'md'
} else {
profile = "pr"
}
const listToPresent = ListEventMapper.toDomain(response, calendarOwnerName, userId)
const map : EventListStore[] = listToPresent.map( element => {
return {
startTime: new Date(element.StartDate),
endTime: new Date(element.EndDate),
allDay: false,
event: element,
calendarName: element.CalendarName,
profile: profile,
id: element.EventId,
CalendarId: userId
}
}) as any
const year = this.listBoxService.list(map, 'md', startDate, endDate, { selectedDate: new Date() })
const events = this.utils.getAllEvents(year)
this.NativeNotificationService.scheduleNotifications(events)
this.memoryStore.pipe(
select(selectEventsInRange(startDate, endDate, userId))
).subscribe((localList)=> {
// console.log({localList})
});
// this.memoryStore.dispatch(removeRangeForCalendar({ startDate, endDate, userId }));
// this.memoryStore.dispatch(pushEvent({ eventsList:eventsList as any, userId, profile }));
return listToPresent
}
)).toPromise()
return ok(result)
@@ -170,6 +218,8 @@ export class AgendaDataRepositoryService {
createEvent(eventData: Event, documents, calendar: TableSharedCalendar, tracing: TracingType) {
console.log('eventData', eventData);
let eventInput = {
userId: calendar.wxUserId,
ownerType: this.utils.selectedCalendarOwner(calendar.role),
@@ -0,0 +1,110 @@
// calendar.actions.ts
import { createAction, props } from '@ngrx/store';
import { createReducer, on } from '@ngrx/store';
import { EventList, EventListStore } from 'src/app/models/agenda/AgendaEventList';
import { createFeatureSelector, createSelector } from '@ngrx/store';
export const loadEvents = createAction('[Calendar] Load Events');
export const loadEventsSuccess = createAction(
'[Calendar] Load Events Success',
props<{ events: EventListStore[] }>()
);
export const resetList = createAction(
'[Calendar] Reset List',
props<{ eventSource: EventListStore[] }>()
);
export const pushEvent = createAction(
'[Calendar] Push Event',
props<{ eventsList: EventList[], profile: 'pr' | 'md', userId: string }>()
);
export const removeRangeForCalendar = createAction(
'[Calendar] Remove Range For Calendar',
props<{ startDate: Date, endDate: Date, userId: string }>()
);
export const getRangeForCalendar = createAction(
'[Calendar] Remove Range For Calendar',
props<{ startDate: Date, endDate: Date, userId: string }>()
);
export const deleteAllEvents = createAction('[Calendar] Delete All Events');
// =========================================================================
export interface CalendarState {
eventSource: EventListStore[];
}
export const initialState: CalendarState = {
eventSource: []
};
export const calendarReducer = createReducer(
initialState,
on(loadEventsSuccess, (state, { events }) => ({
...state,
eventSource: events
})),
on(resetList, (state, { eventSource }) => ({
...state,
eventSource
})),
on(pushEvent, (state, { eventsList, profile, userId }) => {
let news = eventsList.map(element => ({
startTime: new Date(element.StartDate),
endTime: new Date(element.EndDate),
allDay: false,
event: element,
calendarName: element.CalendarName,
profile: profile,
id: element.EventId,
CalendarId: userId
}));
let instance = state.eventSource.concat(news as any);
const ids = instance.map(o => o.id);
const filtered = instance.filter(({ id }, index) => !ids.includes(id, index + 1));
return {
...state,
eventSource: filtered
};
}),
on(removeRangeForCalendar, (state, { startDate, endDate, userId }) => ({
...state,
eventSource: state.eventSource.filter(e =>
!(new Date(e.endTime).getTime() >= new Date(startDate).getTime() &&
new Date(endDate).getTime() >= new Date(e.startTime).getTime() && e.CalendarId == userId)
)
})),
on(deleteAllEvents, state => ({
...state,
eventSource: []
}))
);
// =========================================================================
export const selectCalendarState = createFeatureSelector<CalendarState>('calendar');
export const selectEventSource = createSelector(
selectCalendarState,
(state: CalendarState) => state.eventSource
);
// Create selector to get range of events
export const selectEventsInRange = (startDate: Date, endDate: Date, userId: string) => createSelector(
selectEventSource,
(events) => events.filter(event =>
new Date(event.startTime).getTime() >= new Date(startDate).getTime() &&
new Date(event.endTime).getTime() <= new Date(endDate).getTime() &&
event.CalendarId === userId
)
);
+58 -4
View File
@@ -1,14 +1,15 @@
import { Injectable } from '@angular/core';
import { AgendaDataService } from './agenda-data.service';
import { EventsService } from '../../events.service';
import { RoleIdService } from 'src/app/services/role-id.service'
import { TableSharedCalendar } from './agenda-local-data-source.service';
@Injectable({
providedIn: 'root'
})
export class Utils {
constructor(
private agendaDataService: AgendaDataService,
public eventService: EventsService,
public RoleIdService: RoleIdService,
) { }
@@ -84,7 +85,7 @@ export class Utils {
documents.forEach(element => {
let object = {
docId: element.docId || element.DocId || element.Id,
sourceName: element.subject || element.sourceNames || element.Description || element.SourceName,
sourceName: element.subject || element.sourceNames || element.Description || element.SourceName || element.Assunto,
description: "",
applicationId: element.applicationId || element.ApplicationId
}
@@ -93,7 +94,7 @@ export class Utils {
});
return listupdate.filter( e=> typeof e.docId == 'number')
/* return documents.map((e) => {
return {
docId: e.docId,
@@ -201,4 +202,57 @@ export class Utils {
diff + pad(Math.floor(Math.abs(tzOffset) / 60)) +
':' + pad(Math.abs(tzOffset) % 60);
}
didEventHappenToday(eventTime) {
const eventDate = new Date(eventTime);
const today = new Date();
return eventDate.toDateString() === today.toDateString();
}
duration(date1Str, date2Str) {
// Convert string dates to Date objects
const date1: any = new Date(date1Str);
const date2: any = new Date(date2Str);
// Calculate the difference in milliseconds
const timeDifferenceMs = date2 - date1;
// Convert difference to days, hours, and minutes
const totalMinutes = Math.floor(timeDifferenceMs / (1000 * 60));
const days = Math.floor(totalMinutes / (60 * 24));
const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
const minutes = totalMinutes % 60;
return `${days}d ${hours}h ${minutes}m`.replace('0d', '')
}
getAllEvents(years: any[]): Event[] {
const events: Event[] = [];
years.forEach(year => {
year.months.forEach(month => {
month.days.forEach(day => {
events.push(...day.events);
});
});
});
return events;
}
hasPrCalendar(data: TableSharedCalendar[]) {
for(const e of data) {
if(e.roleId == this.RoleIdService.PRES) {
return true
}
}
return false
}
}
+4 -2
View File
@@ -2,6 +2,7 @@ import { Injectable } from '@angular/core';
import { CustomCalendarEvent, EventListStore } from 'src/app/models/agenda/AgendaEventList';
import { DateService } from '../date.service';
import { momentG } from 'src/plugin/momentG';
import { NativeNotificationService } from 'src/app/services/native-notification.service';
@Injectable({
providedIn: 'root'
@@ -12,7 +13,7 @@ export class ListBoxService {
constructor(
private dateService: DateService
private dateService: DateService,
){}
@@ -78,7 +79,8 @@ export class ListBoxService {
// console.log('newStracture', newStracture)
return this.display(newStracture, selectedDate).year
const data = this.display(newStracture, selectedDate)
return data.year
// const daysStringNum = Object.keys(daysObject)
@@ -60,7 +60,6 @@ export class ChatSystemService {
private sortService: SortService,
private ChatService: ChatService,
private NfService: NfService,
private changeProfileService: ChangeProfileService,
private chatService: ChatService,
private ChatMethodsService: ChatMethodsService,
private AESEncrypt: AESEncrypt,
+14 -6
View File
@@ -1,17 +1,14 @@
import { Injectable } from '@angular/core';
import { Event, EventToApproveEdit, } from '../models/event.model';
import { Event } from '../models/event.model';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable, from } from 'rxjs';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { AuthService } from '../services/auth.service';
import { EventList } from '../models/agenda/AgendaEventList';
import { ChangeProfileService } from './change-profile.service';
import { OfflineManagerService } from 'src/app/services/offline-manager.service';
import { catchError } from "rxjs/operators";
import { SessionStore } from '../store/session.service';
import { calendarInterface } from '../models/user.model';
import { Subscribe } from './subcribe';
import { EventOutputDTO } from './Repositorys/Agenda/model/eventDTOOutput';
@Injectable({
@@ -1368,7 +1365,18 @@ export class EventsService {
params = params.set("notifyUsers", true)
const calendar = this.DetectCalendars(CalendarId)
const header = this.makeHeader(calendar)
let header;
console.log('calendar')
try {
header = this.makeHeader(calendar)
} catch (error) {}
console.log('header')
options = {
headers: header,
+164 -19
View File
@@ -1,36 +1,28 @@
import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';
import { CapacitorConfig } from '@capacitor/cli';
/* import { LocalNotifications, LocalNotificationSchema } from '@capacitor/local-notifications'; */
import { LocalNotifications } from '@capacitor/local-notifications';
import { v4 as uuidv4 } from 'uuid'
@Injectable({
providedIn: 'root'
})
export class NativeNotificationService {
constructor(private platform: Platform,) {
private scheduledEventIds: number[] = [];
constructor(
private platform: Platform,) {
this.askForPermission()
}
askForPermission() {
/* LocalNotifications.requestPermissions()
LocalNotifications.checkPermissions().then((data)=>{
//
}).catch((data)=>{
//
}) */
window['send'] = () => {
this.eventNotification({eventId:uuidv4()})
}
}
foregroundNotification() {
askForPermission() {}
/* LocalNotifications.addListener('localNotificationReceived', (notification) => {
}) */
}
foregroundNotification() {}
backgroundNotification() {
/* LocalNotifications.addListener('localNotificationActionPerformed', (action) => {
@@ -53,6 +45,142 @@ export class NativeNotificationService {
}
uuidTo32BitInt(uuid) {
// Remove hyphens and convert to a 16-byte hex string
const hex = uuid.replace(/-/g, '');
// Get the least significant 8 bytes (16 hex characters)
const leastSignificantBytes = hex.slice(-16);
// Convert to a 64-bit integer
const bigInt = BigInt('0x' + leastSignificantBytes);
// Convert to a 32-bit integer and ensure it fits within the int32 range
const int32 = Number(bigInt % BigInt(2 ** 32));
// Adjust to fit within the signed 32-bit range
return int32 >= 2 ** 31 ? int32 - 2 ** 32 : int32;
}
async cancelNotification(eventId: number) {
await LocalNotifications.cancel({ notifications: [{ id: eventId }] });
console.log(`Notification with event ID ${eventId} canceled.`);
}
didEventHappenToday(eventTime) {
const eventDate = new Date(eventTime);
const today = new Date();
return eventDate.toDateString() === today.toDateString();
}
async cancelAllNotification() {
try {
await LocalNotifications.cancel({
notifications: []
});
console.log('All notifications cancelled');
} catch (error) {
console.error('Error cancelling notifications:', error);
}
}
async scheduleNotifications(events: any) {
const notifications = [];
console.log({events});
events = events
.filter(e => new Date().getTime() <= new Date(e.start).getTime())
.filter(e => this.didEventHappenToday(e.start))
console.log('notify', events)
await this.cancelAllNotification();
for (const event of events) {
const eventTime = new Date(event.start).getTime();
const now = new Date().getTime();
// Schedule notifications for 1 hour before and 15 minutes before the event
const oneHourBefore = eventTime - 60 * 60 * 1000;
const fifteenMinutesBefore = eventTime - 15 * 60 * 1000;
const timeDifference = eventTime - now;
const oneHour = 60 * 60 * 1000; // 1 hour in milliseconds
const fifteenMinutes = 15 * 60 * 1000; // 15 minutes in milliseconds
console.log('notification to notify object', event)
// if (timeDifference <= fifteenMinutes) {
// console.log({notification: event, e: '15 minutes'})
// notifications.push({
// title: 'Event Reminder',
// body: `Reminder: ${event.Subject} starts in ${this.duration(event.start, new Date())} minutes.£`,
// id: this.uuidTo32BitInt(event.event.id)
// });
// } else if (timeDifference <= oneHour) {
// console.log({notification: event, e: '1 hour.'})
// notifications.push({
// title: 'Event Reminder',
// body: `Reminder: ${event.Subject} starts in ${this.duration(event.start, new Date())} hour.£`,
// id: this.uuidTo32BitInt(event.id)
// });
// } else {
// console.log("Event is more than 1 hour away.")
if (timeDifference >= fifteenMinutes) {
notifications.push({
title: 'Event Reminder',
body: `Reminder: ${event.event.Subject} 15 minutes`,
id: this.uuidTo32BitInt(event.id)+1,
schedule: { at: new Date(fifteenMinutesBefore) },
});
console.log('15m', new Date(fifteenMinutesBefore))
}
if (timeDifference >= oneHour) {
notifications.push({
title: 'Event Reminder',
body: `Reminder: ${event.event.Subject} 1 hour`,
id: this.uuidTo32BitInt(event.id)+2,
schedule: { at: new Date(oneHourBefore) },
});
console.log('1h', new Date(oneHourBefore))
}
// }
}
await LocalNotifications.schedule({ notifications });
}
async eventNotification({eventId}) {
await LocalNotifications.schedule({
notifications: [
{
title: 'Test Notification 6',
body: 'This is a test notification. 6',
id: this.uuidTo32BitInt(eventId), // Unique ID for the notification
schedule: { at: new Date(Date.now() + 1000 * 10) }, // Schedule to show in 5 seconds
sound: null,
attachments: null,
actionTypeId: '',
extra: null,
},
],
});
console.log('send notificatino')
}
isDesktop() {
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
return true
@@ -62,4 +190,21 @@ export class NativeNotificationService {
}
}
duration(date1Str, date2Str) {
// Convert string dates to Date objects
const date1: any = new Date(date1Str);
const date2: any = new Date(date2Str);
// Calculate the difference in milliseconds
const timeDifferenceMs = date2 - date1;
// Convert difference to days, hours, and minutes
const totalMinutes = Math.floor(timeDifferenceMs / (1000 * 60));
const days = Math.floor(totalMinutes / (60 * 24));
const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
const minutes = totalMinutes % 60;
return `${days}d ${hours}h ${minutes}m`.replace('0d', '')
}
}