change folder path

This commit is contained in:
Peter Maquiran
2024-07-31 11:29:26 +01:00
parent 2d2f00cb4c
commit ba5de9e6d7
52 changed files with 191 additions and 263 deletions
@@ -0,0 +1,41 @@
interface attendees {
EmailAddress : string
Name: string
UserType: string
attendeeType: string
wxUserId: string
Id: string
}
type Changes = {
insert: attendees[];
remove: attendees[];
};
export function AttendeesLIstChangeDetector(
localList: attendees[],
serverList: attendees[]
): Changes {
const changes: Changes = { insert: [], remove: [] };
const localMap = new Map(localList.map(item => [item.wxUserId, item]));
const serverMap = new Map(serverList.map(item => [item.wxUserId, item]));
// Detect new or updated items
for (const [id, serverItem] of serverMap) {
const localItem = localMap.get(id);
if (!localItem) {
changes.insert.push(serverItem);
}
}
// Detect deleted items
for (const [id, localItem] of localMap) {
if (!serverMap.has(id)) {
changes.remove.push(localItem);
}
}
return changes;
}
@@ -0,0 +1,37 @@
import { z } from "zod";
import { SharedCalendarListItemOutputDTO } from "../../data/dto/sharedCalendarOutputDTO";
type Changes = {
insert: SharedCalendarListItemOutputDTO[];
update: SharedCalendarListItemOutputDTO[];
remove: SharedCalendarListItemOutputDTO[];
};
export function SharedCalendarListDetectChanges(
localList: SharedCalendarListItemOutputDTO[],
serverList: SharedCalendarListItemOutputDTO[]
): Changes {
const changes: Changes = { insert: [], update: [], remove: [] };
const localMap = new Map(localList.map(item => [item.wxUserId, item]));
const serverMap = new Map(serverList.map(item => [item.wxUserId, item]));
// Detect new or updated items
for (const [id, serverItem] of serverMap) {
const localItem = localMap.get(id);
if (!localItem) {
changes.insert.push(serverItem);
} else if (localItem.wxFullName !== serverItem.wxFullName) {
changes.update.push(serverItem);
}
}
// Detect deleted items
for (const [id, localItem] of localMap) {
if (!serverMap.has(id)) {
changes.remove.push(localItem);
}
}
return changes;
}
@@ -0,0 +1,41 @@
interface attendees {
EmailAddress : string
Name: string
UserType: string
attendeeType: string
wxUserId: string
Id: string
}
type Changes = {
insert: attendees[];
remove: attendees[];
};
export function AttendeesLIstChangeDetector(
localList: attendees[],
serverList: attendees[]
): Changes {
const changes: Changes = { insert: [], remove: [] };
const localMap = new Map(localList.map(item => [item.wxUserId, item]));
const serverMap = new Map(serverList.map(item => [item.wxUserId, item]));
// Detect new or updated items
for (const [id, serverItem] of serverMap) {
const localItem = localMap.get(id);
if (!localItem) {
changes.insert.push(serverItem);
}
}
// Detect deleted items
for (const [id, localItem] of localMap) {
if (!serverMap.has(id)) {
changes.remove.push(localItem);
}
}
return changes;
}
@@ -0,0 +1,37 @@
import { z } from "zod";
import { SharedCalendarListItemOutputDTO } from "../../dto/sharedCalendarOutputDTO";
type Changes = {
insert: SharedCalendarListItemOutputDTO[];
update: SharedCalendarListItemOutputDTO[];
remove: SharedCalendarListItemOutputDTO[];
};
export function SharedCalendarListDetectChanges(
localList: SharedCalendarListItemOutputDTO[],
serverList: SharedCalendarListItemOutputDTO[]
): Changes {
const changes: Changes = { insert: [], update: [], remove: [] };
const localMap = new Map(localList.map(item => [item.wxUserId, item]));
const serverMap = new Map(serverList.map(item => [item.wxUserId, item]));
// Detect new or updated items
for (const [id, serverItem] of serverMap) {
const localItem = localMap.get(id);
if (!localItem) {
changes.insert.push(serverItem);
} else if (localItem.wxFullName !== serverItem.wxFullName) {
changes.update.push(serverItem);
}
}
// Detect deleted items
for (const [id, localItem] of localMap) {
if (!serverMap.has(id)) {
changes.remove.push(localItem);
}
}
return changes;
}
@@ -0,0 +1,133 @@
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { EventInputDTO } from '../dto/eventInputDTO';
import { SessionStore } from 'src/app/store/session.service';
import { SharedCalendarListOutputDTO } from '../dto/sharedCalendarOutputDTO';
import { EventOutputDTO } from '../dto/eventDTOOutput';
import { AttendeesRemoveInputDTO } from '../dto/attendeeRemoveInputDTO';
import { EventListOutputDTO } from '../dto/eventListDTOOutput';
import { HttpService } from 'src/app/services/http.service';
import { TracingType } from 'src/app/services/monitoring/opentelemetry/tracer';
@Injectable({
providedIn: 'root'
})
export class AgendaDataService {
private baseUrl = 'https://gdapi-dev.dyndns.info/stage/api/v2'; // Your base URL
constructor(
private http: HttpClient,
private httpService: HttpService
) { }
// Documents Endpoints
getAttachments(subject: string, applicationType: number) {
const params = {
Subject: subject,
ApplicationType: applicationType.toString()
}
return this.httpService.get<any>(`${this.baseUrl}/Documents/Attachments`, { params });
}
viewDocument(userId: number, docId: number, applicationId: number) {
const params = new HttpParams()
.set('userId', userId.toString())
.set('docId', docId.toString())
.set('applicationId', applicationId.toString());
return this.httpService.get<any>(`${this.baseUrl}/Documents/view`, params);
}
// Events Endpoints
createEvent(eventData: EventInputDTO) {
return this.httpService.post<any>(`${this.baseUrl}/Events`, eventData);
}
// @APIReturn(EventListOutputDTOSchema, 'get/Events')
getEvents({userId, startDate, endDate, status, category, type }, tracing?: TracingType) {
let params: any = {
UserId: userId
}
if(userId == null || userId == undefined) {
throw('userId '+ userId)
}
if(status != null || status != undefined) {
params.status = status;
}
if (startDate !== null && startDate !== undefined) {
params.startDate = startDate;
}
if (endDate !== null && endDate !== undefined) {
params.endDate = endDate;
}
return this.httpService.get<EventListOutputDTO>(`${this.baseUrl}/Events`, params, tracing);
}
searchEvent(queryParameter: {value, status}) {
return this.httpService.get<EventListOutputDTO>(`${this.baseUrl}/Events`, queryParameter);
}
getEvent(id: string, tracing?: TracingType) {
return this.httpService.get<EventOutputDTO>(`${this.baseUrl}/Events/${id}`, {}, tracing);
}
updateEvent(id: string, eventData: any) {
return this.httpService.put<any>(`${this.baseUrl}/Events/${id}`, eventData);
}
approveEvent(id: string) {
return this.httpService.patch<any>(`${this.baseUrl}/Events/${id}/Approval`, {});
}
async deleteEvent(id: string, deleteAllEvents: boolean) {
const params = {
'DeleteAllEvents': deleteAllEvents.toString()
};
return this.httpService.delete<any>(`${this.baseUrl}/Events/${id}`, params);
}
updateEventStatus(id: string, statusData: Object) {
return this.httpService.patch<any>(`${this.baseUrl}/Events/${id}/Status`, statusData);
}
addEventAttendee(id: string, attendeeData: any): Observable<any> {
return this.http.post<any>(`${this.baseUrl}/Events/${id}/Attendee`, attendeeData);
}
removeEventAttendee(id: string, attendeeData: AttendeesRemoveInputDTO): Observable<any> {
return this.http.delete<any>(`${this.baseUrl}/Events/${id}/Attendee`, { body: attendeeData });
}
addEventAttachment(id: string, attachmentData: any): Observable<any> {
return this.http.post<any>(`${this.baseUrl}/Events/${id}/Attachment`, attachmentData);
}
removeEventAttachment(id: string, attachmentData: any): Observable<any> {
return this.http.delete<any>(`${this.baseUrl}/Events/${id}/Attachment`, { body: attachmentData });
}
getDocumentAttachment(aplicationId,userId,value,PageNumber,PageSize): Observable<any> {
const params = new HttpParams()
.set('userId', userId)
.set('Value', value)
.set('PageNumber', PageNumber)
.set('PageSize', PageSize);
return this.http.get<any>(`${this.baseUrl}/Documents/Attachments${aplicationId}`, {params});
}
// @APIReturn(SharedCalendarListOutputDTOSchema, 'Users/${SessionStore.user.UserId}/ShareCalendar')
async getSharedCalendar() {
return await this.httpService.get<SharedCalendarListOutputDTO>(`${this.baseUrl}/Users/${SessionStore.user.UserId}/ShareCalendar`);
}
}
@@ -0,0 +1,123 @@
import { Injectable } from '@angular/core';
import { Dexie, EntityTable, liveQuery } from 'Dexie';
import { any, z } from 'zod';
import { err, ok } from 'neverthrow';
import { from } from 'rxjs';
import { SharedCalendarListItemOutputDTO } from '../dto/sharedCalendarOutputDTO';
const tableScharedCalendar = z.object({
wxUserId: z.number(),
wxFullName: z.string(),
wxeMail: z.string().email(),
role: z.string(),
roleId: z.number(),
shareType: z.number(),
date: z.string(),
})
export type TableSharedCalendar = z.infer<typeof tableScharedCalendar>
// Database declaration (move this to its own module also)
export const AgendaDataSource = new Dexie('AgendaDataSource') as Dexie & {
shareCalendar: EntityTable<TableSharedCalendar, 'wxUserId'>;
};
AgendaDataSource.version(1).stores({
shareCalendar: 'wxUserId, wxFullName, wxeMail, role, roleId, shareType, startDate, endDate'
});
@Injectable({
providedIn: 'root'
})
export class AgendaLocalDataSourceService {
constructor() { }
async bulkCreate(data: SharedCalendarListItemOutputDTO[]) {
// db.eve
try {
const result = await AgendaDataSource.shareCalendar.bulkAdd(data)
return ok(result)
} catch (e) {
return err(false)
}
}
async clearAndAddRecords(data: SharedCalendarListItemOutputDTO[]) {
try {
await AgendaDataSource.transaction('rw', AgendaDataSource.shareCalendar, async () => {
// Clear existing records from myTable
await AgendaDataSource.shareCalendar.clear();
await AgendaDataSource.shareCalendar.bulkAdd(data);
});
console.log('Clear and add operations completed within transaction.');
} catch (error) {
console.error('Error performing transaction:', error, data);
}
}
async createCalendar(data: SharedCalendarListItemOutputDTO) {
// db.eve
try {
const result = await AgendaDataSource.shareCalendar.add(data)
return ok(result)
} catch (e) {
return err(false)
}
}
async removeCalendar(data: SharedCalendarListItemOutputDTO) {
// db.eve
try {
const result = await AgendaDataSource.shareCalendar.delete(data.wxUserId)
return ok(result)
} catch (e) {
return err(false)
}
}
clearSharedCalendar() {
// db.eve
try {
const result = AgendaDataSource.shareCalendar.clear()
return ok(result)
} catch (e) {
return err(false)
}
}
async geCalendars() {
return await AgendaDataSource.shareCalendar.toArray()
}
getShareCalendarItemsLive() {
return from(liveQuery( () => {
return AgendaDataSource.shareCalendar.toArray()
}))
}
// New method to get calendars by wxUserId
async getCalendarByUserId(wxUserId: number) {
try {
const result = await AgendaDataSource.shareCalendar.get(wxUserId)
if(!result) {
const list = await AgendaDataSource.shareCalendar.toArray()
const found = list.find(e => e.wxUserId == wxUserId)
if(found) {
return ok(found)
} else {
return err('404')
}
} else {
return ok(result)
}
} catch (e) {
return err(false);
}
}
}
@@ -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
)
);
@@ -0,0 +1,13 @@
import { z } from 'zod';
export const AttachInputDTOSchema = z.object({
attachments: z.array(z.object({
docId: z.any(),
sourceName: z.any(),
description: z.any().nullable(),
applicationId: z.any(),
}))
})
export type AttachInputDTO = z.infer<typeof AttachInputDTOSchema>
@@ -0,0 +1,14 @@
import { z } from 'zod';
export const AttendeeInputDTOSchema = z.array(z.object({
name: z.string(),
emailAddress: z.string(),
attendeeType: z.number(),
wxUserId: z.number(),
userType: z.enum(['GD','External', 'Internal']),
entity: z.string()
}))
export type AttendeeInputDTO = z.infer<typeof AttendeeInputDTOSchema>
@@ -0,0 +1,8 @@
import { z } from "zod"
export const AttendeesRemoveInputDTOSchema = z.object({
attendees: z.array(z.string()),
})
export type AttendeesRemoveInputDTO = z.infer<typeof AttendeesRemoveInputDTOSchema>
+50
View File
@@ -0,0 +1,50 @@
export enum EEventFilterStatus {
All = -1,
Pending = 1,
Revision,
Approved,
Declined,
Communicated,
ToCommunicate,
AllToCommunicate, // approvado e to communicate
PendingEvents,
}
// Define your TypeScript enum
export enum EEventStatus {
Pending = 1,
Revision,
Approved,
Declined,
Communicated,
ToCommunicate,
}
export enum EEventCategory
{
Oficial = 1,
Pessoal
}
export enum EEventOwnerType {
PR = 1,
MD,
Others
}
export enum EEventType
{
Meeting = 1,
Travel,
Conference,
}
export enum EAttendeeType {
Required = 1,
Acknowledgment,
Optional
}
@@ -0,0 +1,79 @@
import { z } from 'zod';
import { EAttendeeType, EEventCategory, EEventOwnerType, EEventStatus, EEventType } from './enums';
export const AttachmentInputDTOSchema = z.object({
id: z.string().nullable(),
docId: z.number().nullable(),
sourceName: z.string().nullable(),
description: z.string().nullable(),
applicationId: z.number().int(),
}).strict();
const EAttendeeTypeDTO = z.nativeEnum(EAttendeeType);
const CommentSchema = z.object({
message: z.string(),
createdAt: z.string(),
});
const AttendeeSchema = z.object({
id: z.string(),
name: z.string(),
attendeeType: z.nativeEnum(EAttendeeType), // ["Required", "Acknowledgment", "Optional"] = [1,2,3]
emailAddress: z.string(),
wxUserId: z.number(),
});
const OwnerSchema = z.object({
wxUserId: z.number(),
wxFullName: z.string(),
wxeMail: z.string(),
userPhoto: z.string(),
});
const OrganizerSchema = z.object({
wxUserId: z.number(),
wxFullName: z.string(),
wxeMail: z.string(),
userPhoto: z.string(),
});
const EventRecurrenceSchema = z.object({
Type: z.number().optional(),
Day: z.any().optional(),
DayOfWeek: z.any(),
Month: z.any(),
LastOccurrence: z.any().optional(),
frequency: z.number().optional(),
until: z.string().optional()
}).nullable()
export const EventOutputDTOSchema = z.object({
success: z.boolean(),
message: z.string(),
data: z.object({
id: z.string(),
owner: OwnerSchema,
ownerType: z.nativeEnum(EEventOwnerType), // ["PR", "MD", "Other"] = [1,2,3],
subject: z.string(),
body: z.string(),
location: z.string(),
startDate: z.string(),
endDate: z.string(),
type: z.nativeEnum(EEventType),
category: z.nativeEnum(EEventCategory), // ['Oficial', 'Pessoal'] = [1, 2]
attendees: z.array(AttendeeSchema),
isRecurring: z.boolean(),
eventRecurrence: EventRecurrenceSchema,
hasAttachments: z.boolean(),
attachments: z.array(AttachmentInputDTOSchema),
comments: z.array(CommentSchema),
isPrivate: z.boolean(),
isAllDayEvent: z.boolean(),
organizer: OrganizerSchema,
status: z.nativeEnum(EEventStatus), // ['Pending', 'Revision', 'Approved', 'Declined', 'Communicated', 'ToCommunicate'] = [1, 2, 3, 4, 5, 6]
}),
})
export type EventOutputDTO = z.infer<typeof EventOutputDTOSchema>
@@ -0,0 +1,42 @@
import { z } from 'zod';
import { EEventCategory, EEventOwnerType, EEventType } from './enums';
const attendeeSchema = z.object({
name: z.string(),
emailAddress: z.string(),
attendeeType: z.number(),
wxUserId: z.number(),
userType: z.enum(['GD','External', 'Internal']),
entity: z.string()
});
const attachmentSchema = z.object({
docId: z.number(),
sourceName: z.string(),
description: z.string(),
applicationId: z.number()
});
const recurrenceSchema = z.object({
frequency: z.number(),
until: z.string().nullable().optional()
});
export const EventInputDTOSchema = z.object({
userId: z.number(),
ownerType: z.nativeEnum(EEventOwnerType),
subject: z.string(),
body: z.string(),
location: z.string(),
startDate: z.string(),
endDate: z.string(),
type: z.nativeEnum(EEventType),
category: z.nativeEnum(EEventCategory),
attendees: z.array(attendeeSchema),
attachments: z.array(attachmentSchema),
recurrence: recurrenceSchema,
organizerId: z.number(),
isAllDayEvent: z.boolean()
});
export type EventInputDTO = z.infer<typeof EventInputDTOSchema>
@@ -0,0 +1,40 @@
import { z } from 'zod';
import { EEventCategory, EEventOwnerType, EEventStatus, EEventType } from './enums';
const OwnerSchema = z.object({
wxUserId: z.number(),
wxFullName: z.string(),
wxeMail: z.string(),
userPhoto: z.string(),
});
export const EventListOutputDTOSchema = z.object({
id: z.string(),
owner: OwnerSchema,
ownerType: z.nativeEnum(EEventOwnerType),// ['MD','PR', 'Other'] // Assuming "MD" is the only valid option based on provided data
subject: z.string(),
body: z.string().optional(),
location: z.string().nullable(),
startDate: z.string().datetime({ offset: true }),
endDate: z.string().datetime({ offset: true }),
type: z.nativeEnum(EEventType), // ['Meeting', 'Travel'] = [1,2 ]
// category: z.enum(['Oficial', 'Pessoal']), // Assuming "Oficial" is the only valid option based on provided data
category: z.nativeEnum(EEventCategory),
isRecurring: z.boolean(),
eventRecurrence: z.any().nullable(),
hasAttachments: z.boolean(),
isPrivate: z.boolean(),
isAllDayEvent: z.boolean(),
// status: z.enum(['Approved']), // Assuming "Approved" is the only valid option based on provided data
status: z.nativeEnum(EEventStatus), // Assuming "Approved" is the only valid option based on provided data
createdAt: z.string().datetime({ offset: true }),
})
export const EventListDataOutputDTOSchema = z.object({
success: z.boolean(),
message: z.string(),
data: z.array(EventListOutputDTOSchema),
}).nullable();
export type EventListOutputDTO = z.infer<typeof EventListDataOutputDTOSchema>;
@@ -0,0 +1,12 @@
import { z } from 'zod';
import { EEventOwnerType } from './enums';
export const EventSearchOutputDTOSchema = z.object({
Id: z.string(),
subject: z.string(),
dateEntry: z.string(),
Data: z.string(),
entity: z.string().optional()
}).nullable();
export type EventSearchOutput = z.infer<typeof EventSearchOutputDTOSchema>;
@@ -0,0 +1,39 @@
import { z } from "zod";
import { EEventOwnerType, EEventType, EEventCategory, EEventStatus } from "./enums";
const OwnerSchema = z.object({
wxUserId: z.number(),
wxFullName: z.string(),
wxeMail: z.string(),
userPhoto: z.string(),
});
const EventToApproveList = z.array(z.object({
id: z.string().uuid(),
owner: OwnerSchema,
ownerType: z.nativeEnum(EEventOwnerType),
subject: z.string(),
body: z.string().nullable().optional(),
location: z.string().nullable(),
startDate: z.string().datetime({ offset: true }),
endDate: z.string().datetime({ offset: true }),
type: z.nativeEnum(EEventType),
category: z.nativeEnum(EEventCategory),
isRecurring: z.boolean(),
eventRecurrence: z.any().nullable(),
hasAttachments: z.boolean(),
isPrivate: z.boolean(),
isAllDayEvent: z.boolean(),
status: z.nativeEnum(EEventStatus)
}))
export const EventToApproveDataOutputDTOSchema = z.object({
success: z.boolean(),
message: z.string(),
data: EventToApproveList,
}).nullable();
export type EventToApproveListOutputDTO = z.infer<typeof EventToApproveDataOutputDTOSchema>;
@@ -0,0 +1,25 @@
import { z } from 'zod';
import { EEventCategory, EEventOwnerType, EEventType } from './enums';
const recurrenceSchema = z.object({
frequency: z.number(),
until: z.string().nullable().optional()
});
export const EventUpdateInputDTOSchema = z.object({
userId: z.number(),
ownerType: z.nativeEnum(EEventOwnerType),
subject: z.string(),
body: z.string().optional(),
location: z.string(),
startDate: z.string(),
endDate: z.string(),
type: z.nativeEnum(EEventType),
category: z.nativeEnum(EEventCategory),
recurrence: recurrenceSchema,
isAllDayEvent: z.boolean(),
updateAllEvents: z.boolean()
});
export type EventUpdateInputDTO = z.infer<typeof EventUpdateInputDTOSchema>
@@ -0,0 +1,20 @@
import { z } from "zod";
const SharedCalendarListItemOutputDTOSchema = z.object({
wxUserId: z.number(),
wxFullName: z.string(),
wxeMail: z.string().email(),
role: z.string(),
roleId: z.number(),
shareType: z.number(),
date: z.string(),
})
export const SharedCalendarListOutputDTOSchema = z.object({
success: z.boolean(),
message: z.string(),
data: z.array(SharedCalendarListItemOutputDTOSchema),
}).nullable();
export type SharedCalendarListItemOutputDTO = z.infer<typeof SharedCalendarListItemOutputDTOSchema>;
export type SharedCalendarListOutputDTO = z.infer<typeof SharedCalendarListOutputDTOSchema>;
@@ -0,0 +1,360 @@
import { Injectable } from '@angular/core';
import { AgendaDataService } from '../data-source/agenda-data.service';
import { map } from 'rxjs/operators';
import { ListEventMapper } from '../../domain/mapper/EventListMapper';
import { EventMapper } from '../../domain/mapper/EventDetailsMapper';
import { Event } from 'src/app/models/event.model';
import { SessionStore } from 'src/app/store/session.service';
import { EventListToApproveMapper } from '../../domain/mapper/eventToApproveListMapper';
import { err, ok } from 'neverthrow';
import { HttpErrorResponse } from '@angular/common/http';
import { EventToApproveDetailsMapper } from '../../domain/mapper/EventToApproveDetailsMapper';
import { AgendaLocalDataSourceService, TableSharedCalendar } from '../data-source/agenda-local-data-source.service';
import { EEventFilterStatus } from '../dto/enums';
import { EventToApproveDataOutputDTOSchema } from '../dto/eventToApproveListOutputDTO';
import { EventOutputDTOSchema } from '../dto/eventDTOOutput';
import { SharedCalendarListDetectChanges } from '../async/change/shareCalendarChangeDetector';
import { SharedCalendarListItemOutputDTO } from '../dto/sharedCalendarOutputDTO';
import { EventUpdateInputDTOSchema } from '../dto/eventUpdateInputDtO';
import { AttachInputDTOSchema } from '../dto/addAttachmentDTOInput';
import { EventListDataOutputDTOSchema } from '../dto/eventListDTOOutput';
import { EventSearchMapper } from '../../domain/mapper/EventSearchMapper';
import { select, Store } from '@ngrx/store';
import { CalendarState, pushEvent, removeRangeForCalendar, selectEventsInRange } from '../data-source/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';
import { AttendeeInputDTOSchema } from '../dto/attendeeInputDTO';
import { EventInputDTOSchema } from '../dto/eventInputDTO';
import { Utils } from 'src/app/module/agenda/utils';
import { APINODReturn } from 'src/app/services/decorator/api-validate-schema.decorator';
import { TracingType } from 'src/app/services/monitoring/opentelemetry/tracer';
import { isHttpError } from 'src/app/services/http.service';
@Injectable({
providedIn: 'root'
})
export class AgendaDataRepositoryService {
constructor(
private agendaDataService: AgendaDataService,
private utils: Utils,
private agendaLocalDataSourceService: AgendaLocalDataSourceService,
private memoryStore: Store<CalendarState>,
private NativeNotificationService: NativeNotificationService,
public listBoxService: ListBoxService,
) { }
createOwnCalendar(): SharedCalendarListItemOutputDTO {
const currentUserCalendar = {
wxUserId: SessionStore.user.UserId,
wxFullName: SessionStore.user.FullName,
wxeMail: SessionStore.user.Email,
role: SessionStore.user.RoleDescription,
roleId: SessionStore.user.RoleID,
shareType: 3,
date: '',
}
return currentUserCalendar
}
async getEventById(id: string, tracing?: TracingType) {
const result = await this.agendaDataService.getEvent(id, tracing)
if(result.isOk()) {
APINODReturn(EventOutputDTOSchema, result.value, `get/Events/${id}`, tracing)
return result.map(e => EventMapper.toDomain(e))
}
return result
}
async getEventToApproveById(id: string, tracing?: TracingType) {
const result = await this.agendaDataService.getEvent(id)
if(result.isOk()) {
APINODReturn(EventOutputDTOSchema, result.value, `get/Events/${id}`, tracing)
return result.map(e => EventToApproveDetailsMapper.toDomain(e))
}
return result
}
async searchEvent(queryParameters: {value, status}, tracing?: TracingType) {
const result = await this.agendaDataService.searchEvent(queryParameters)
return result.map( response => {
APINODReturn(EventListDataOutputDTOSchema, response, 'get/Events', tracing)
return EventSearchMapper.toDomain(response, "calendarOwnerName", "userId")
})
}
async EventList({ userId, startDate, endDate, status = EEventFilterStatus.Approved, category = null, type = null, calendarOwnerName = '' }, tracing?: TracingType) {
const result = await this.agendaDataService.getEvents({userId, startDate, endDate, status, category, type})
if(result.isOk()) {
return result.map(response => {
APINODReturn(EventListDataOutputDTOSchema, response, 'get/Events', tracing)
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:listToPresent as any, userId, profile }));
return listToPresent
})
}
return result
}
async eventToApproveList({ userId, startDate = null, endDate = null, status = EEventFilterStatus.Pending, category = null, type = null, calendarOwnerName = '' }, tracing?: TracingType) {
const result = await this.agendaDataService.getEvents({userId, startDate : null, endDate: null, status, category: null, type: null}, tracing)
return result.map(response => {
APINODReturn(EventToApproveDataOutputDTOSchema, response, 'get/ApproveList', tracing)
return EventListToApproveMapper.toDomain(response, calendarOwnerName, userId)
})
}
createEvent(eventData: Event, documents, calendar: TableSharedCalendar, tracing: TracingType, addAll =false) {
console.log('eventData', eventData);
let eventInput = {
userId: calendar.wxUserId,
ownerType: this.utils.selectedCalendarOwner(calendar.role),
subject: eventData.Subject,
body: eventData.Body.Text,
location: eventData.Location,
startDate: this.utils.addOneHourToIsoString(eventData.StartDate.toISOString()),
endDate: this.utils.addOneHourToIsoString(eventData.EndDate.toISOString()),
type: this.utils.calendarTypeSeleted(eventData.Category),
category: this.utils.calendarCategorySeleted(eventData.CalendarName),
attendees: this.utils.attendeesAdded(eventData.Attendees),
attachments: this.utils.documentAdded(documents, addAll),
recurrence: {
frequency: this.utils.eventRecurence(eventData.EventRecurrence.frequency),
until:((eventData.EventRecurrence.until === "") ? this.utils.addOneHourToIsoString(eventData.EndDate.toISOString()) : eventData.EventRecurrence.until),
},
organizerId: SessionStore.user.UserId,
isAllDayEvent: eventData.IsAllDayEvent,
}
APINODReturn(EventInputDTOSchema, eventInput, 'post/Events', tracing)
return this.agendaDataService.createEvent(eventInput)
}
updateEvent(eventId, eventData, editAllEvent, calendar: TableSharedCalendar, tracing: TracingType) {
let body;
if(typeof eventData?.Body == 'object') {
body = eventData?.Body?.Text
} else {
body = eventData?.Body
}
let eventInput = {
userId: calendar.wxUserId,
ownerType: this.utils.selectedCalendarOwner(calendar.role),
subject: eventData.Subject,
body: eventData?.Body?.Text,
location: eventData.Location,
startDate: this.utils.addOneHourToIsoString(eventData.StartDate),
endDate: this.utils.addOneHourToIsoString(eventData.EndDate),
isAllDayEvent: eventData.IsAllDayEvent,
updateAllEvents: editAllEvent,
type: this.utils.calendarTypeSeleted(eventData.Category),
category: this.utils.calendarCategorySeleted(eventData.CalendarName || eventData.Agenda),
recurrence: {
frequency: this.utils.eventRecurence(eventData.EventRecurrence.frequency),
until: ((eventData.EventRecurrence.until === "") ? this.utils.addOneHourToIsoString(eventData.EndDate.toISOString()) : eventData.EventRecurrence.until),
}
}
console.log({eventData})
console.log({eventInput})
APINODReturn(EventUpdateInputDTOSchema, eventInput, 'PUT/Events', tracing)
return this.agendaDataService.updateEvent(eventId, eventInput)
}
addEventAttendee(id, attendeeData, tracing?: TracingType) {
console.log(attendeeData)
console.log(this.utils.attendeesEdit(attendeeData))
const data = { attendees: this.utils.attendeesAdded(attendeeData) }
APINODReturn(AttendeeInputDTOSchema, data, `PUT/Events/${id}/Attendee`, tracing)
return this.agendaDataService.addEventAttendee(id, { attendees: this.utils.attendeesAdded(attendeeData) });
}
removeEventAttendee(id, attendeeData: {Id : string}[]) {
return this.agendaDataService.removeEventAttendee(id, { attendees: attendeeData.map(e => e.Id || e['id']) } );
}
addEventAttachment(id, attachmentData, tracing: TracingType) {
console.log(attachmentData)
const attachments = { attachments: this.utils.documentAdded(attachmentData, false) }
APINODReturn(AttachInputDTOSchema, attachments, `POST/${id}/Attendee`, tracing)
return this.agendaDataService.addEventAttachment(id, attachments);
}
deleteEvent(eventId,deleteAll) {
return this.agendaDataService.deleteEvent(eventId, deleteAll)
}
removeEventAttachment(eventId, attachmentData) {
return this.agendaDataService.removeEventAttachment(eventId, attachmentData);
}
async deleteEvent1(eventId) {
return await this.agendaDataService.deleteEvent(eventId, false)
}
eventToaprovalStatus(eventId, status, comment: string) {
let statusObject = {
status: this.utils.statusEventAproval(status),
comment: comment
}
return this.agendaDataService.updateEventStatus(eventId, statusObject)
}
getDocumentAttachments(applicationId, userId, subject, pageNumber, pageSize) {
return this.agendaDataService.getDocumentAttachment(applicationId, userId, subject, pageNumber, pageSize)
}
async getSharedCalendar() {
const result = await this.agendaDataService.getSharedCalendar()
const localList = await this.agendaLocalDataSourceService.geCalendars()
if (result.isOk()) {
if(!result.value?.data) {
result.value.data = [this.createOwnCalendar()]
} else {
result.value.data.push(this.createOwnCalendar())
}
const { remove, insert, update } = SharedCalendarListDetectChanges(localList, result.value.data)
for(const item of insert) {
this.agendaLocalDataSourceService.createCalendar(item)
}
for(const item of remove) {
this.agendaLocalDataSourceService.removeCalendar(item)
}
} else {
if(isHttpError(result.error)) {
if (result.error.status == 404) {
const remove = localList.filter(e => e.wxUserId != SessionStore.user.UserId)
for(const item of remove) {
this.agendaLocalDataSourceService.removeCalendar(item)
}
}
}
const item = this.createOwnCalendar()
this.agendaLocalDataSourceService.createCalendar(item)
}
}
async clearSharedCalendar() {
return await this.agendaLocalDataSourceService.clearSharedCalendar()
}
getShareCalendarItemsLive() {
return this.agendaLocalDataSourceService.getShareCalendarItemsLive()
}
getShareCalendarItemsLiveWithOrder() {
// Define the role priorities
const rolePriorities: { [key: number]: number } = {
100000014: 1, // Presidente da República
100000011: 2, // Vice Presidente (example role ID)
// Add other roles with their priorities here
};
return this.getShareCalendarItemsLive().pipe(
map(data => data.sort((a, b) => {
console.log('Raw data:', data); // Debug line
const priorityA = rolePriorities[a.roleId] || Infinity;
const priorityB = rolePriorities[b.roleId] || Infinity;
return priorityA - priorityB;
}))
)
}
async geCalendars() {
return await this.agendaLocalDataSourceService.geCalendars()
}
approveEvent(eventId) {
return this.agendaDataService.approveEvent(eventId);
}
async getCalendarByUserId(wxUserId: number) {
return await this.agendaLocalDataSourceService.getCalendarByUserId(wxUserId)
}
}
@@ -0,0 +1,137 @@
import { EEventCategory, EEventOwnerType, EEventStatus, EAttendeeType } from "../../data/dto/enums";
import { EventOutputDTO } from "../../data/dto/eventDTOOutput";
function getTextInsideParentheses(inputString) {
var startIndex = inputString.indexOf('(');
var endIndex = inputString.indexOf(')');
if (startIndex !== -1 && endIndex !== -1) {
return inputString.substring(startIndex + 1, endIndex);
} else {
return null;
}
}
export class EventMapper {
constructor() {}
static toDomain(_dto: EventOutputDTO) {
const dto = _dto.data;
let category;
if(dto.category == EEventCategory.Oficial) {
category = 'Oficial'
} else {
category = 'Pessoal'
}
let ownerType;
if(dto.ownerType == EEventOwnerType.PR) {
ownerType = 'PR'
} else if(dto.ownerType == EEventOwnerType.MD) {
ownerType = 'MD'
} else if(dto.ownerType == EEventOwnerType.Others) {
ownerType = 'Other'
}
let type;
let status;
if(dto.status == EEventStatus.Pending) {
status = 'Pending'
} else if(dto.status == EEventStatus.Revision) {
status = 'Revision'
}
function FEAttendeeType(num) {
if(num == EAttendeeType.Required) {
return 'Required'
} else if (num == EAttendeeType.Acknowledgment) {
return 'Acknowledgment'
} else if (num == EAttendeeType.Optional) {
return 'Optional'
}
}
return {
"owner": dto.owner,
"HasAttachments": dto.hasAttachments,
"EventComunicationId": 1682,
"EventId": dto.id,
"Subject": dto.subject,
"Body": {
"BodyType": 1,
"Text": dto.body
},
"Location": dto.location,
"CalendarId": "",
"CalendarName": category,
"StartDate": dto.startDate,
"EndDate": dto.endDate,
"EventType": "Single",
"Attendees": dto.attendees.map((e) => ({
Id: e.id,
wxUserId: e.wxUserId,
EmailAddress: e.emailAddress,
Name: e.name,
IsRequired: FEAttendeeType(e.attendeeType) == 'Required',
UserType: "GD",
// "IsPR": false,
attendeeType: FEAttendeeType(e.attendeeType)
// "RoleDescription": null,
// "RoleId": 0
})),
"Status": status,
"IsMeeting": category,
"IsRecurring": dto.isRecurring,
"IsAllDayEvent": dto.isAllDayEvent,
"AppointmentState": 1,
"TimeZone": getTextInsideParentheses(new Date(dto.startDate)+ ''),
"Organizer": {
"Id": dto.organizer.wxUserId,
"EmailAddress": dto.organizer.wxeMail,
"Name": dto.organizer.wxFullName,
"IsRequired": true,
"UserType": 'GD',
"IsPR": ownerType == 'PR',
//"Entity": null,
"Acknowledgment": true,
//"RoleDescription": null,
//"RoleId": 0
},
"InstanceId": null,
"Category": dto.type,
"EventRecurrence": {
"Type": -1,
"Day": null,
"DayOfWeek": null,
"Month": null,
"LastOccurrence": null,
"frequency": dto?.eventRecurrence?.frequency,
"until": dto?.eventRecurrence?.until
},
"Attachments": dto.attachments.map( e => ({
"Id": e.id,
// "ParentId": "AAMkADVhOGY3ZDQzLTg4ZGEtNDYxMC1iMzc5LTJkMDgwNjMxOWFlZQBGAAAAAABEDW9nKs69TKQcVqQURj8YBwBR2HR2eO7pSpNdD9cc70l+AAAAAAFKAABR2HR2eO7pSpNdD9cc70l+AACK2OeJAAA=",
// "Source": 1,
"SourceId": e.docId,
// "Description": "teste pp",
"SourceName": e.sourceName,
// "CreateDate": "2024-05-24 16:41",
// "Stakeholders": "",
// "Link": "",
// "Data": null,
"ApplicationId": e.applicationId,
// "FileSize": 301208
})),
"IsPrivate": dto.isPrivate
}
}
static toDTO(data: any): any {
return {}
}
}
@@ -0,0 +1,79 @@
import { EventList } from "src/app/models/entiry/agenda/eventList"
import { XTracer } from "src/app/services/monitoring/opentelemetry/tracer";
import { EEventCategory, EEventOwnerType, EEventType, EEventStatus } from "../../data/dto/enums";
import { EventListOutputDTO } from "../../data/dto/eventListDTOOutput";
function getTextInsideParentheses(inputString): string {
var startIndex = inputString.indexOf('(');
var endIndex = inputString.indexOf(')');
if (startIndex !== -1 && endIndex !== -1) {
return inputString.substring(startIndex + 1, endIndex);
} else {
return null;
}
}
export class ListEventMapper {
// @XTracer({name:'ListEventMapper/toDomain', log: false, bugPrint: false})
static toDomain(dto: EventListOutputDTO, calendarOwnerName: string, userId: string): EventList {
return dto.data.map((e) => {
let category;
if(e.category == EEventCategory.Oficial) {
category = 'Oficial'
} else {
category = 'Pessoal'
}
let ownerType;
if(e.ownerType == EEventOwnerType.PR) {
ownerType = 'PR'
} else if(e.ownerType == EEventOwnerType.MD) {
ownerType = 'MD'
} else if(e.ownerType == EEventOwnerType.Others) {
ownerType = 'Other'
}
let type;
if(e.type == EEventType.Meeting) {
type = 'Meeting'
} else if (e.type == EEventType.Travel) {
type = 'Travel'
}
let status;
if(e.status == EEventStatus.Pending) {
status = 'Pending'
} else if(e.status == EEventStatus.Revision) {
status = 'Revision'
} else if(e.status == EEventStatus.Approved) {
status = 'Approved'
} else if(e.status == EEventStatus.Declined) {
status = 'Declined'
}
return {
"HasAttachments": e.hasAttachments,
"IsAllDayEvent": e.isAllDayEvent,
"EventId": e.id,
"Subject": e.subject,
"Location": e.location,
"CalendarId": (e.owner.wxUserId) as any,
"CalendarName": category,
"StartDate": new Date(e.startDate) + '',
"EndDate": new Date(e.endDate)+ '',
"Schedule": (e.owner.wxFullName) as any,
"RequiredAttendees": null as any,
"OptionalAttendees": null as any,
"HumanDate": "2 semanas atrás" as any,
"TimeZone": getTextInsideParentheses(new Date(e.startDate)+ ''),
"IsPrivate": false as any,
"createdAt": e.createdAt
}
})
}
static toDTO() {}
}
@@ -0,0 +1,37 @@
import { SearchList } from "src/app/models/search-document";
import { EventListOutputDTO } from "../../data/dto/eventListDTOOutput";
function getTextInsideParentheses(inputString): string {
var startIndex = inputString.indexOf('(');
var endIndex = inputString.indexOf(')');
if (startIndex !== -1 && endIndex !== -1) {
return inputString.substring(startIndex + 1, endIndex);
} else {
return null;
}
}
export class EventSearchMapper {
// @XTracer({name:'ListEventMapper/toDomain', log: false, bugPrint: false})
static toDomain(dto: EventListOutputDTO, calendarOwnerName: string, userId: string): SearchList[] {
return dto.data.map((e) => {
return {
Id: e.id as any,
subject: e.subject,
dateEntry: e.createdAt as any,
Data: e.createdAt as any,
entity: (e.owner.wxFullName),
ApplicationType: 0 as any,
Assunto: e.subject,
appName: "string",
ApplicationName: "",
docId: e.id as any,
applicationId: 0 as any
}
})
}
static toDTO() {}
}
@@ -0,0 +1,191 @@
import { EventToApproveDetails } from "src/app/models/entiry/agenda/eventToApproveDetails"
import { EEventCategory, EEventOwnerType, EEventStatus, EAttendeeType } from "../../data/dto/enums";
import { EventOutputDTO } from "../../data/dto/eventDTOOutput";
function getTextInsideParentheses(inputString) {
var startIndex = inputString.indexOf('(');
var endIndex = inputString.indexOf(')');
if (startIndex !== -1 && endIndex !== -1) {
return inputString.substring(startIndex + 1, endIndex);
} else {
return null;
}
}
export class EventToApproveDetailsMapper {
constructor() {}
static toDomain(_dto: EventOutputDTO): EventToApproveDetails {
let dto = _dto.data
let category;
if(dto.category == EEventCategory.Oficial) {
category = 'Oficial'
} else {
category = 'Pessoal'
}
let color;
if(dto.ownerType == EEventOwnerType.PR) {
color = 'PR'
} else {
color = 'MDGPR'
}
// if(dto.ownerType != 'PR') {
let ownerType;
if(dto.ownerType == EEventOwnerType.PR) {
ownerType = 'PR'
} else if(dto.ownerType == EEventOwnerType.MD) {
ownerType = 'MD'
} else if(dto.ownerType == EEventOwnerType.Others) {
ownerType = 'Other'
}
let activityInstanceName;
let taskStatus;
if(dto.status == EEventStatus.Pending) {
activityInstanceName = 'Aprovar evento'
taskStatus = 'Pending' //////
} else if(dto.status == EEventStatus.Revision) {
activityInstanceName = 'Editar evento'
taskStatus = 'Revision' //////
} else if (dto.status == EEventStatus.Approved) {
activityInstanceName = 'Evento Aprovado'
taskStatus = 'Approved' //////
} else if (dto.status == EEventStatus.Declined) {
activityInstanceName = 'Declined'
taskStatus = 'Declined' //////
} else if (dto.status == EEventStatus.Communicated) {
activityInstanceName = 'Communicated'
taskStatus = 'Communicated' //////
} else if (dto.status == EEventStatus.ToCommunicate) {
activityInstanceName = 'ToCommunicate'
taskStatus = 'ToCommunicate' //////
}
function FEAttendeeType(num) {
if(num == EAttendeeType.Required) {
return 'Required'
} else if (num == EAttendeeType.Acknowledgment) {
return 'Acknowledgment'
} else if (num == EAttendeeType.Optional) {
return 'Optional'
}
}
let status;
if(dto.status == EEventStatus.Pending) {
status = 'Pending'
} else if(dto.status == EEventStatus.Revision) {
status = 'Revision'
}
return {
"owner": dto.owner,
"serialNumber": dto.id,
"taskStatus": taskStatus,
"originator": {
"email": dto.organizer.wxeMail,
"manager": "",
"displayName": "",
// "fqn": "K2:gabinetedigital\\dlima",
// "username": "gabinetedigital\\dlima"
},
// "isDelegated": false,
// "isExtended": false,
// "hasTakenAcknowledge": false,
// "actions": [
// "Reenviar",
// "Descartar"
// ],
"activityInstanceName": activityInstanceName,
// "workflowInstanceFolio": "MTk4",
// "taskStartDate": "2024-04-10T14:30:39.58",
// "deadline": null,
// "workflowID": 24744,
// "workflowInstanceID": 47026,
//"workflowName": "Agenda\\Agenda Oficial MDGPR",
"workflowDisplayName": `Agenda ${category} ${color}`,
//"formURL": "http://bpmdev.gabinetedigital.local/Runtime/Runtime/Form/Exchange+Calendar+Meeting+Edition/?SerialNo=47026_169&ProcessInstanceID=&InstanceId=",
"workflowInstanceDataFields": {
"Body": dto.body,
"Location": dto.location,
"Subject": dto.subject,
"StartDate": dto.startDate,
"EndDate": dto.endDate,
// "Participants": "evilarinho@gabinetedigital.local",
// "CC": "",
// "ReviewUserComment": "{\r\n \"option\": \"save\",\r\n \"note\": \"\"\r\n}",
// "Role": 100000011,
// "MDName": "Eduardo Vilarinho",
// "MDEmail": "evilarinho@gabinetedigital.local",
// "OriginatorComments": "",
"Status": status,
"TimeZone": getTextInsideParentheses(new Date(dto.startDate)+ ''),
"Agenda": category ,
"EventType": dto.type,
//"EventID": "",
//"HasAttachments": true,
"ParticipantsList": [
...dto.attendees.map( e => ({
Id: e.id,
Name: e.name,
EmailAddress: e.emailAddress,
IsRequired: FEAttendeeType(e.attendeeType) == 'Required',
UserType: "GD",
wxUserId: e.wxUserId,
attendeeType: FEAttendeeType(e.attendeeType)
}))
],
//"EventOrganizer": "{\"$type\":\"GabineteDigital.k2RESTidentifier_EventPerson, GabineteDigital, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\",\"EmailAddress\":\"agenda.mdgpr@gabinetedigital.local\",\"Name\":\"Agenda do Ministro e Director do Gabinete do PR\",\"IsRequired\":true}",
"CreateEvent": "",
"IsAllDayEvent": false,
//"SerializedItem": "",
//"MDwxUserID": 198,
//"DeserializedItem": "",
//"Message": "Foi adicionado para a sua agenda um evento com o assunto: Event to approve MD, para a vossa aprovação",
//"InstanceId": "AGD_dlima_2024-04-10_14:30:39.453",
//"For Each Result": "",
//"For Each Index": 0,
//"Header": "",
//"RecurringString": "",
//"LastOccurrence": "",
//"OccurrenceType": "-1",
//"SerialNumber": "",
//"For Each Result 1": "false",
//"For Each Index 1": 0,
//"UserEmail": "",
//"LastActivInstanceID": "78",
"IsRecurring": false,
//"CalendarId": "AQMkAGVhZWZkOGM0LWNiZjMtNGE4Ny05NTY4LWZjMTEANTE2MWU4YmUALgAAAwkDRuPtBKJItLDcu6efhYABACLK19NpGvtHh8oQYZPTW2sAAAIBSgAAAA==",
//"wxUserID": 312
},
"totalDocuments": null,
"Documents": null,
"PrivateMessage": null,
Attachments: dto.attachments.map( e => ({
id: e.id,
DocId: e.docId,
Description: e.sourceName,
Stakeholders: '',
CreateDate: '',
ApplicationId: e.applicationId,
})),
eventRecurrence: {
frequency: dto?.eventRecurrence?.frequency,
until: dto?.eventRecurrence?.until
}
}
}
static toDTO(data: any): any {
return {}
}
}
@@ -0,0 +1,113 @@
import { EventToApproveList } from "src/app/models/entiry/agenda/eventToApproveList";
import { EEventCategory, EEventOwnerType, EEventStatus } from "../../data/dto/enums";
import { EventToApproveListOutputDTO } from "../../data/dto/eventToApproveListOutputDTO";
function getTextInsideParentheses(inputString): string {
var startIndex = inputString.indexOf('(');
var endIndex = inputString.indexOf(')');
if (startIndex !== -1 && endIndex !== -1) {
return inputString.substring(startIndex + 1, endIndex);
} else {
return null;
}
}
export class EventListToApproveMapper {
static toDomain(dtoList: EventToApproveListOutputDTO, calendarOwnerName: string, userId: string): EventToApproveList {
return dtoList.data.map((dto) => {
let category;
if(dto.category == EEventCategory.Oficial) {
category = 'Oficial'
} else {
category = 'Pessoal'
}
let color;
let workflowDisplayName;
if(dto.ownerType == EEventOwnerType.PR) {
color = 'PR'
workflowDisplayName = `Agenda ${category} ${color}`
} else {
color = 'MDGPR'
workflowDisplayName = `Agenda ${category} ${color}`
}
// else {
// workflowDisplayName = `Agenda ${category}`
// }
let activityInstanceName;
let taskStatus;
if(dto.status == EEventStatus.Pending) {
activityInstanceName = 'Aprovar evento'
taskStatus = 'Pending' //////
} else if(dto.status == EEventStatus.Revision) {
activityInstanceName = 'Editar evento'
taskStatus = 'Revision' //////
} else if (dto.status == EEventStatus.Approved) {
activityInstanceName = 'Evento Aprovado'
taskStatus = 'Approved' //////
} else if (dto.status == EEventStatus.Declined) {
activityInstanceName = 'Declined'
taskStatus = 'Declined' //////
} else if (dto.status == EEventStatus.Communicated) {
activityInstanceName = 'Communicated'
taskStatus = 'Communicated' //////
} else if (dto.status == EEventStatus.ToCommunicate) {
activityInstanceName = 'ToCommunicate'
taskStatus = 'ToCommunicate' //////
}
return {
serialNumber: dto.id,
taskStatus: taskStatus,
taskStartDate: dto.startDate,
taskReceiveDate: dto.startDate,
deadline: null,
workflowDisplayName,
activityInstanceName,
totalDocuments: 0,
workflowInstanceDataFields: {
Agenda: category,
EndDate: dto.endDate,
StartDate: dto.startDate,
Subject: dto.subject,
Location: dto.location,
Status: "Active",
IsAllDayEvent: dto.isAllDayEvent,
InstanceId: "",
originator: ""
}
}
})
}
static toDTO() {}
}
// "serialNumber": "47315_184",
// "taskStatus": "Open",
// "taskStartDate": "2024-04-24T11:27:12.527",
// "taskReceiveDate": "2024-04-24T11:29:17.76",
// "deadline": null,
// "workflowDisplayName": "Agenda Oficial PR",
// "activityInstanceName": "Comunicar Evento",
// "totalDocuments": 0,
// "workflowInstanceDataFields": {
// "Agenda": "Oficial",
// "EndDate": "2024-04-25 11:30:00",
// "StartDate": "2024-04-24 11:30:00",
// "Subject": "Event 2 After MERGE",
// "Location": "lUANDA",
// "Status": "Active",
// "IsAllDayEvent": false,
// "InstanceId": "AAMkADVhOGY3ZDQzLTg4ZGEtNDYxMC1iMzc5LTJkMDgwNjMxOWFlZQBGAAAAAABEDW9nKs69TKQcVqQURj8YBwBR2HR2eO7pSpNdD9cc70l+AAAAAAFKAABR2HR2eO7pSpNdD9cc70l+AACK2Od9AAA=",
// "originator": "dlima@gabinetedigital.local"
// }
+269
View File
@@ -0,0 +1,269 @@
import { Injectable } from '@angular/core';
import { EventsService } from 'src/app/services/events.service';
import { RoleIdService } from 'src/app/services/role-id.service'
import { TableSharedCalendar } from './data/data-source/agenda-local-data-source.service';
@Injectable({
providedIn: 'root'
})
export class Utils {
constructor(
public eventService: EventsService,
public RoleIdService: RoleIdService,
) { }
selectedCalendarUserId(CalendarName, postEvent) {
if (this.eventService.calendarNamesType[CalendarName]?.['Oficial'] && postEvent.CalendarName == 'Oficial') {
return this.eventService.calendarNamesType[CalendarName]['OwnerId']
} else if (this.eventService.calendarNamesType[CalendarName]?.['Pessoal'] && postEvent.CalendarName == 'Pessoal') {
return this.eventService.calendarNamesType[CalendarName]['OwnerId']
} else {
return '11:11'
}
}
selectedCalendarOwner(roleDescription) {
console.log('roleDescription', roleDescription)
if (roleDescription) {
if (roleDescription == "Presidente da República") {
return 1;
} else if (roleDescription == "Ministro e Director do Gabinete do PR") {
return 2
} else {
return 3
}
}
}
findRoleIdByUserId(array, userId) {
for (let item of array) {
console.log('each item before',item)
if (typeof item === 'object' && item !== null && item.OwnerUserId === parseInt(userId)) {
console.log('each item after',item)
return item.Role;
} else {
return 'other';
}
}
}
calendarCategorySeleted(calendarName) {
var selectedCalendar = {
'Oficial': 1,
'Pessoal': 2
}
if(calendarName != 'Pessoal' && calendarName != 'Oficial') {
throw('bad logic')
}
return selectedCalendar[calendarName];
}
calendarTypeSeleted(calendarName) {
var selectedType = {
'Meeting': 1,
'Travel': 2,
'Conference': 3,
'Encontro': 1,
'Reunião': 1,
'Conferência': 3
}
return selectedType[calendarName];
}
documentAdded(documents: any[], addAll: Boolean) {
console.log('added doc create event', documents)
let listupdate = []
documents.forEach(element => {
let object = {
docId: element.SourceId || element.docId || element.DocId || element.Id,
sourceName: element.subject || element.sourceNames || element.Description || element.SourceName || element.Assunto,
description: "",
applicationId: element.applicationId || element.ApplicationId
}
listupdate.push(object)
});
console.log({listupdate})
return listupdate.filter( e=> typeof e.docId == 'number' || addAll)
/* return documents.map((e) => {
return {
docId: e.docId,
sourceName: e.subject || e.sourceNames,
description: "",
applicationId: e.applicationId
};
}); */
}
editDocumentAdded(documents: any[]) {
console.log('document added', documents)
return documents.map((element) => {
return {
docId: parseInt(element.SourceId),
sourceName: element.SourceName,
description: "",
applicationId: parseInt(element.ApplicationId)
};
});
}
atendeesSeletedType(type) {
var selectedType = {
'true': 1,
'false': 2,
'other': 3,
}
return selectedType[type];
}
attendeesAdded(taskParticipants: any[]) {
console.log({taskParticipants});
return taskParticipants.map((e) => {
return {
name: e.Name,
emailAddress: e.EmailAddress,
attendeeType: this.atendeesSeletedType(JSON.stringify(e.IsRequired)),
wxUserId: e.Id,
userType: e.UserType,
entity: e.Entity,
}
});
}
statusEventAproval(type) {
var selectedType = {
'Pending': 1,
'Revision': 2,
'Approved': 3,
"Declined": 4,
"Communicated": 5
}
return selectedType[type];
}
attendeesEdit(taskParticipants: any[]) {
return taskParticipants.map((e) => {
return {
name: e.Name,
emailAddress: e.EmailAddress,
attendeeType: this.atendeesSeletedType(JSON.stringify(e.IsRequired)),
wxUserId: e.wxUserId || e.Id,
userType: e.UserType,
entity: e.Entity,
}
});
}
eventRecurence(type) {
var selectedType = {
'never': 0,
'daily': 1,
'weekly': 2,
"monthly": 3,
"yearly": 4
}
return selectedType[type];
}
recurenceTypeSeleted(recurenceType) {
var selectedType = {
0: 'never',
1: 'daily',
2: 'weekly',
3: 'monthly',
4: 'yearly'
}
return selectedType[recurenceType];
}
addOneHourToIsoString(isoDateString) {
let date = new Date(isoDateString);
const tzOffset = -date.getTimezoneOffset(); // in minutes
const diff = tzOffset >= 0 ? '+' : '-';
const pad = (n: number) => (n < 10 ? '0' : '') + n;
return date.getFullYear() +
'-' + pad(date.getMonth() + 1) +
'-' + pad(date.getDate()) +
'T' + pad(date.getHours()) +
':' + pad(date.getMinutes()) +
':' + pad(date.getSeconds()) +
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
}
}