diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 8e8816e52..96d5670a8 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -1,5 +1,5 @@ - + diff --git a/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml index ddb26ad77..c7bd21dbd 100644 --- a/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml +++ b/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -1,34 +1,34 @@ - - - - - - - - - - - + + + + + + + + + + + diff --git a/android/app/src/main/res/drawable/ic_launcher_background.xml b/android/app/src/main/res/drawable/ic_launcher_background.xml index 3a37cf6d0..d5fccc538 100644 --- a/android/app/src/main/res/drawable/ic_launcher_background.xml +++ b/android/app/src/main/res/drawable/ic_launcher_background.xml @@ -1,170 +1,170 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml index 67820c56d..036d09bc5 100644 --- a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -1,5 +1,5 @@ - - - - + + + + \ No newline at end of file diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml index 67820c56d..036d09bc5 100644 --- a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -1,5 +1,5 @@ - - - - + + + + \ No newline at end of file diff --git a/doc/architecture.md b/doc/architecture.md index 5166922b4..47034a173 100644 --- a/doc/architecture.md +++ b/doc/architecture.md @@ -52,44 +52,42 @@ The project is divided into several key sections, each serving a specific purpos - **utils**: Utility functions and constants. -├── package-lock.json -├── package.json -├── src -│ ├── common -│ ├── core -│ │ ├── attachment -│ │ │ ├── entity -│ │ │ ├── repository +├── package-lock.json +├── package.json +├── src +│ ├── common +│ ├── core +│ │ ├── chat +│ │ │ ├── entity +│ │ │ ├── repository │ │ │ └── use-cases -│ ├── module -│ │ ├── gabinete -│ │ │ ├── domain -│ │ │ ├── data -│ │ ├── Agenda -│ │ │ ├── domain -│ │ │ ├── data -│ ├── UI -│ │ ├── pages -│ │ │ ├── share -| │ │ │ ├── buttons -│ │ │ │ └── modal +│ ├── module +│ │ ├── agenda +│ │ │ ├── domain +│ │ │ ├── data +│ │ ├── chat +│ │ │ ├── domain +│ │ │ ├── data +│ ├── UI +│ │ ├── pages +│ │ │ ├── share +| │ │ │ ├── buttons +│ │ │ │ └── modal │ │ │ ├── Home -│ │ │ | ├── service -│ │ │ │ └── store -│ │ │ ├── Agenda -│ │ │ ├── Gabinete -│ │ │ ├── Actions -│ │ │ ├── Chat -│ ├── infra +│ │ │ | ├── service +│ │ │ │ └── store +│ │ │ ├── Agenda +│ │ │ ├── Chat +│ ├── infra │ │ ├── http │ │ ├── socket │ │ ├── database -│ │ ├── camera -│ ├── utils -│ │ ├── date.ts -│ │ ├── exception.ts -│ │ ├── sort.ts -│ ├── libs +│ │ ├── camera +│ ├── utils +│ │ ├── date.ts +│ │ ├── exception.ts +│ │ ├── sort.ts +│ ├── libs ## Achieving Reusability diff --git a/readme.md b/readme.md index 17262e8d5..8a60cb411 100644 --- a/readme.md +++ b/readme.md @@ -30,6 +30,9 @@ Java version 11 ionic build && npx cap add android && npx cap update +Gradle version 7.4.1 +Gradle SDK JDK 16.0.2 + ## BUG @@ -97,3 +100,4 @@ git tag stable For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate. + diff --git a/src/app/Rules/user.service.spec.ts b/src/app/Rules/user.service.spec.ts deleted file mode 100644 index 3f804c9fd..000000000 --- a/src/app/Rules/user.service.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { TestBed } from '@angular/core/testing'; - -import { UserService } from './user.service'; - -describe('UserService', () => { - let service: UserService; - - beforeEach(() => { - TestBed.configureTestingModule({}); - service = TestBed.inject(UserService); - }); - - it('should be created', () => { - expect(service).toBeTruthy(); - }); -}); diff --git a/src/app/Rules/user.service.ts b/src/app/Rules/user.service.ts deleted file mode 100644 index 172eeb441..000000000 --- a/src/app/Rules/user.service.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { Injectable } from '@angular/core'; - -@Injectable({ - providedIn: 'root' -}) -export class UserService { - - constructor() { } - - changeProfilePicture(){} - -} diff --git a/src/app/app.component.ts b/src/app/app.component.ts index 4e9395928..552415fe7 100644 --- a/src/app/app.component.ts +++ b/src/app/app.component.ts @@ -9,6 +9,7 @@ import { Storage } from '@ionic/storage'; import { register } from 'swiper/element/bundle'; import { DomSanitizer } from '@angular/platform-browser'; import { ScreenOrientation } from "@ionic-native/screen-orientation/ngx"; +import { SessionStore } from './store/session.service'; const CUSTOM_DATE_FORMATS: NgxMatDateFormats = { parse: { dateInput: "YYYY-MMMM-DD HH:mm" @@ -31,6 +32,8 @@ register(); ] }) export class AppComponent { + tabIsActive = true + constructor( private platform: Platform, private statusBar: StatusBar, @@ -67,6 +70,27 @@ export class AppComponent { } } + + window.addEventListener('focus', (event) => { + if (!this.tabIsActive) { + this.tabIsActive = true + const data = SessionStore.getDataFromLocalStorage(); + + if (!data?.user?.Authorization && SessionStore?.user?.Authorization) { + window.location.reload(); + } + + if (window['all-process-gabinete']) { + window['all-process-gabinete']() + } + } + }); + + window.addEventListener('blur', (event) => { + this.tabIsActive = false + }); + + } /* requestPermission() { diff --git a/src/app/app.module.ts b/src/app/app.module.ts index ddf0a29e4..6d89de9da 100644 --- a/src/app/app.module.ts +++ b/src/app/app.module.ts @@ -86,15 +86,14 @@ import { CreateProcessPage } from './modals/create-process/create-process.page'; import { LoggingInterceptorService } from './services/logging-interceptor.service'; import { PopupQuestionPipe } from './modals/popup-question.pipe'; import '@teamhive/capacitor-video-recorder'; -import { tokenInterceptor } from './interceptors/token.interceptors'; -import { chatTokenInterceptor } from './interceptors/chatToken.interceptor'; +import { tokenInterceptor } from './infra/monitoring/interceptors/token.interceptors'; import { InputFilterDirective } from './services/directives/input-filter.directive'; import { VisibilityDirective } from './services/directives/visibility.directive'; import { DeplomaOptionsPageModule } from './shared/popover/deploma-options/deploma-options.module'; import { DiplomaOptionsPage } from './shared/popover/deploma-options/deploma-options.page'; import { ImageCropperModule } from 'ngx-image-cropper'; -import { metricsInterceptor } from './interceptors/metter.interceptor'; +import { metricsInterceptor } from './infra/monitoring/interceptors/metter.interceptor'; import {MatMenuModule} from '@angular/material/menu'; import {MatIconModule} from '@angular/material/icon'; @@ -104,6 +103,7 @@ import { openTelemetryLogging } from './services/monitoring/opentelemetry/loggin import { registerLocaleData } from '@angular/common'; import localePt from '@angular/common/locales/pt'; import { LogsDatabase } from './infra/database/dexie/instance/logs/service'; +import { UserModule } from './module/user/user.module'; // Register the locale data registerLocaleData(localePt, 'pt'); @@ -209,7 +209,8 @@ registerLocaleData(localePt, 'pt'); MatMenuModule, MatIconModule, // module - ChatModule + ChatModule, + UserModule ], entryComponents: [ DiplomaOptionsPage, @@ -251,7 +252,6 @@ registerLocaleData(localePt, 'pt'); FFMpeg, FFmpeg, { provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptorService, multi: true }, - chatTokenInterceptor, tokenInterceptor, metricsInterceptor ], diff --git a/src/app/core/chat/entity/message.ts b/src/app/core/chat/entity/message.ts index aa3326611..235839a51 100644 --- a/src/app/core/chat/entity/message.ts +++ b/src/app/core/chat/entity/message.ts @@ -95,9 +95,11 @@ export class MessageEntity { constructor() {} - get messageStatus() { + get messageHasId() { if(this.id) { - return 'send' + return true + } else { + return false } } diff --git a/src/app/core/chat/repository/room/room-remote-repository.ts b/src/app/core/chat/repository/room/room-remote-repository.ts index 2b6af476c..647f39cea 100644 --- a/src/app/core/chat/repository/room/room-remote-repository.ts +++ b/src/app/core/chat/repository/room/room-remote-repository.ts @@ -5,8 +5,19 @@ import { RoomByIdInputDTO, RoomByIdOutputDTO } from "src/app/core/chat/usecase/r import { RoomUpdateInputDTO, RoomUpdateOutputDTO } from "src/app/core/chat/usecase/room/room-update-by-id-use-case.service"; import { Result } from "neverthrow"; import { AddMemberToRoomInputDTO } from "src/app/core/chat/usecase/member/member-add-use-case.service"; -import { RoomListOutPutDTO } from "src/app/core/chat/usecase/room/room-get-list-use-case.service"; +import { RoomListItemOutPutDTO, RoomListItemSchema, RoomListOutPutDTO } from "src/app/core/chat/usecase/room/room-get-list-use-case.service"; + +export interface ISearchRoom { + + success: boolean, + message: any, + data: { + messages: [], + rooms: RoomListItemSchema[] + } + +} export abstract class IRoomRemoteRepository { abstract createRoom(data: CreateRoomInputDTO): DataSourceReturn abstract getRoomList(): Promise> @@ -14,4 +25,5 @@ export abstract class IRoomRemoteRepository { abstract updateRoom(data: RoomUpdateInputDTO): Promise> abstract deleteRoom(id: string): Promise> abstract addMemberToRoomSocket(data: AddMemberToRoomInputDTO): Promise> + abstract search(input: string): Promise> } diff --git a/src/app/core/chat/usecase/message/message-create-use-case.service copy.ts b/src/app/core/chat/usecase/message/message-create-use-case.service copy.ts new file mode 100644 index 000000000..aa9552a52 --- /dev/null +++ b/src/app/core/chat/usecase/message/message-create-use-case.service copy.ts @@ -0,0 +1,236 @@ +import { Injectable } from '@angular/core'; +import { IMessage, MessageAttachmentSource, MessageEntity, MessageEntitySchema, } from '../../entity/message'; +import { z } from 'zod'; +import { v4 as uuidv4 } from 'uuid'; +import { InstanceId } from '../../../../module/chat/domain/chat-service.service'; +import { createBlobFromBase64, createDataURL } from 'src/app/utils/ToBase64'; +import { zodSafeValidation } from 'src/app/utils/zodValidation'; +import { Logger } from 'src/app/services/logger/main/service'; +import { err, Result } from 'neverthrow'; +import { MessageMapper } from '../../mapper/messageMapper'; +import { RoomType } from "src/app/core/chat/entity/group"; +import { TracingType, XTracerAsync } from 'src/app/services/monitoring/opentelemetry/tracer'; +import { MessageTable } from 'src/app/infra/database/dexie/instance/chat/schema/message'; +import { MessageAttachmentFileType, MessageOutPutDataDTO } from 'src/app/core/chat/repository/dto/messageOutputDTO'; +import { IMessageLocalRepository } from 'src/app/core/chat/repository/message/message-local-repository'; +import { IMessageSocketRepository } from 'src/app/core/chat/repository/message/message-socket-repository'; +import { IMemberLocalRepository } from 'src/app/core/chat/repository/member/member-local-repository'; +import { IAttachmentLocalRepository } from 'src/app/core/chat/repository/typing/typing-local-repository'; +import { base64Schema } from 'src/app/utils/zod'; + + +export const MessageInputDTOSchema = z.object({ + roomId: z.string().uuid().optional(), + receiverId: z.number().optional(), + senderId: z.number(), + message: z.string().nullable().optional(), + messageType: z.number(), + canEdit: z.boolean(), + oneShot: z.boolean(), + requireUnlock: z.boolean(), + requestId: z.string(), + attachment: z.object({ + fileType: z.nativeEnum(MessageAttachmentFileType), + source: z.nativeEnum(MessageAttachmentSource), + file: base64Schema.optional(), + fileName: z.string().optional(), + applicationId: z.number().optional(), + docId: z.number().optional(), + mimeType: z.string().nullable().optional(), + description: z.string().optional() + }).optional() +}); +export type MessageInputDTO = z.infer + + + +export const MessageCreatePutDataDTOSchema = z.object({ + id: z.string(), + roomId: z.string(), + sender: z.object({ + wxUserId: z.number(), + wxFullName: z.string(), + wxeMail: z.string(), + userPhoto: z.string().optional() + }), + message: z.string().nullable().optional(), + messageType: z.number(), + sentAt: z.string(), + canEdit: z.boolean(), + oneShot: z.boolean(), + requireUnlock: z.boolean(), + requestId: z.string().optional().nullable(), + reactions: z.object({ + id: z.string(), + reactedAt: z.string(), + reaction: z.string(), + sender: z.object({}), + }).array(), + info: z.array(z.object({ + memberId: z.number(), + readAt: z.string().nullable(), + deliverAt: z.string().nullable() + })), + attachments: z.array(z.object({ + fileType: z.nativeEnum(MessageAttachmentFileType), + source: z.nativeEnum(MessageAttachmentSource), + file: z.string().optional(), + fileName: z.string().optional(), + applicationId: z.number().optional(), + docId: z.number().optional(), + id: z.string().optional() + })) +}); + +export type MessageCreateOutPutDataDTO = z.infer + +@Injectable({ + providedIn: 'root' +}) +export class MessageCreateUseCaseService { + + constructor( + private AttachmentLocalRepositoryService: IAttachmentLocalRepository, + private messageLocalDataSourceService: IMessageLocalRepository, + private messageSocketRepositoryService: IMessageSocketRepository, + private MemberListLocalRepository: IMemberLocalRepository + ) { } + + + @XTracerAsync({name:'MessageCreateUseCaseService', module:'chat', bugPrint: true, waitNThrow: 5000}) + async execute(message: IMessage, messageEnum: RoomType, tracing?: TracingType) { + + const validation = zodSafeValidation(MessageEntitySchema, message) + + if(validation.isOk()) { + message.sendAttemp++; + + message.requestId = InstanceId +'@'+ uuidv4(); + message.sending = true; + + const createMessageLocally = this.messageLocalDataSourceService.insert(message) + + createMessageLocally.then(async (value) => { + if(value.isOk()) { + + const localId = value.value + message.$id = localId + + if(message.hasAttachment) { + + for (const attachment of message.attachments) { + + if(attachment.source != MessageAttachmentSource.Webtrix) { + + this.AttachmentLocalRepositoryService.insert({ + $messageId: localId, + file: createBlobFromBase64(attachment.file, attachment.mimeType), + fileType: attachment.fileType, + source: attachment.source, + fileName: attachment.fileName, + applicationId: attachment.applicationId, + docId: attachment.docId, + mimeType: attachment.mimeType, + base64: createDataURL(attachment.file, attachment.mimeType) + }).then((e) => { + if(e.isErr()) { + Logger.error('failed to create attachment locally on send message', { + error: e.error, + data: createDataURL(attachment.file, attachment.mimeType).slice(0, 100) +'...' + }) + } + + }) + + attachment.safeFile = createDataURL(attachment.file, attachment.mimeType) + } + } + + } + + + } else { + Logger.error('failed to insert locally', { + error: value.error.message + }) + } + + }).catch((error) => { + Logger.error('failed to insert catch', { + //error: createMessageLocally.error.message + }) + }) + + + let sendMessageResult: Result + + if(messageEnum == RoomType.Group) { + const DTO = MessageMapper.fromDomain(message, message.requestId) + message.sending = true + sendMessageResult = await this.messageSocketRepositoryService.sendGroupMessage(DTO) + } else { + const DTO = MessageMapper.fromDomain(message, message.requestId) + delete DTO.roomId + message.sending = true + sendMessageResult = await this.messageSocketRepositoryService.sendDirectMessage(DTO) + } + + // return this sendMessageResult + + if(sendMessageResult.isOk()) { + + message.id = sendMessageResult.value.id + + console.log('sendMessageResult', sendMessageResult.value.id) + + if(sendMessageResult.value.sender == undefined || sendMessageResult.value.sender == null) { + + delete sendMessageResult.value.sender + } + + let clone: MessageTable = { + ...sendMessageResult.value, + id: sendMessageResult.value.id, + $id : message.$id + } + + createMessageLocally.then(() => { + this.messageLocalDataSourceService.update(message.$id, {...clone, sending: false, roomId: clone.roomId}).then((data)=> { + if(data.isOk()) { + + } else { + tracing.hasError('failed to update send message') + console.log(sendMessageResult) + console.log(data.error) + } + }) + }) + + return sendMessageResult + } else { + Logger.error('failed to send message to the server', { + error: sendMessageResult.error + }) + await this.messageLocalDataSourceService.update(message.$id, {sending: false, $id: message.$id}) + return err('no connection') + } + + + } else { + + if(validation.error.formErrors.fieldErrors.attachments) { + Logger.error('failed to send message doe to invalid attachment', { + zodErrorList: validation.error.errors, + data: message.attachments + }) + } else { + Logger.error('failed to send message, validation failed', { + zodErrorList: validation.error.errors, + data: message + }) + } + + } + + } +} diff --git a/src/app/core/chat/usecase/message/message-create-use-case.service.ts b/src/app/core/chat/usecase/message/message-create-use-case.service.ts index 8bab66c4e..66780feb5 100644 --- a/src/app/core/chat/usecase/message/message-create-use-case.service.ts +++ b/src/app/core/chat/usecase/message/message-create-use-case.service.ts @@ -106,78 +106,96 @@ export class MessageCreateUseCaseService { message.sendAttemp++; message.requestId = InstanceId +'@'+ uuidv4(); - message.sending = true; - const createMessageLocally = await this.messageLocalDataSourceService.insert(message) + const createMessageLocally = this.messageLocalDataSourceService.insert(message) - if(createMessageLocally.isOk()) { + createMessageLocally.then((value) => { + if(value.isOk()) { - message.$id = createMessageLocally.value + console.log("set image") + message.$id = value.value - if(message.hasAttachment) { + if(message.hasAttachment) { - for (const attachment of message.attachments) { + for (const attachment of message.attachments) { - if(attachment.source != MessageAttachmentSource.Webtrix) { + if(attachment.source != MessageAttachmentSource.Webtrix) { - this.AttachmentLocalRepositoryService.insert({ - $messageId: createMessageLocally.value, - file: createBlobFromBase64(attachment.file, attachment.mimeType), - fileType: attachment.fileType, - source: attachment.source, - fileName: attachment.fileName, - applicationId: attachment.applicationId, - docId: attachment.docId, - mimeType: attachment.mimeType, - base64: createDataURL(attachment.file, attachment.mimeType) - }).then((e) => { - if(e.isErr()) { - Logger.error('failed to create attachment locally on send message', { - error: e.error, - data: createDataURL(attachment.file, attachment.mimeType).slice(0, 100) +'...' - }) - } + this.AttachmentLocalRepositoryService.insert({ + $messageId: value.value, + file: createBlobFromBase64(attachment.file, attachment.mimeType), + fileType: attachment.fileType, + source: attachment.source, + fileName: attachment.fileName, + applicationId: attachment.applicationId, + docId: attachment.docId, + mimeType: attachment.mimeType, + base64: createDataURL(attachment.file, attachment.mimeType) + }).then((e) => { + if(e.isErr()) { + Logger.error('failed to create attachment locally on send message', { + error: e.error, + data: createDataURL(attachment.file, attachment.mimeType).slice(0, 100) +'...' + }) + } - }) + }) - attachment.safeFile = createDataURL(attachment.file, attachment.mimeType) + attachment.safeFile = createDataURL(attachment.file, attachment.mimeType) + } } + } - } - //==================== - message.sending = true - - let sendMessageResult: Result - if(messageEnum == RoomType.Group) { - const DTO = MessageMapper.fromDomain(message, message.requestId) - sendMessageResult = await this.messageSocketRepositoryService.sendGroupMessage(DTO) } else { - const DTO = MessageMapper.fromDomain(message, message.requestId) - delete DTO.roomId - sendMessageResult = await this.messageSocketRepositoryService.sendDirectMessage(DTO) + Logger.error('failed to insert locally', { + error: value.error.message + }) } - // return this sendMessageResult + }); - if(sendMessageResult.isOk()) { + //==================== + message.sending = true - message.id = sendMessageResult.value.id + let sendMessageResult!: Result + const start = performance.now(); // Capture the start time + if(messageEnum == RoomType.Group) { + const DTO = MessageMapper.fromDomain(message, message.requestId) + sendMessageResult = await this.messageSocketRepositoryService.sendGroupMessage(DTO) + } else { + const DTO = MessageMapper.fromDomain(message, message.requestId) + delete DTO.roomId + sendMessageResult = await this.messageSocketRepositoryService.sendDirectMessage(DTO) + } - console.log('sendMessageResult', sendMessageResult.value.id) + const end = performance.now(); // Capture the end time + const duration = end - start; // Calculate the difference - if(sendMessageResult.value.sender == undefined || sendMessageResult.value.sender == null) { + tracing.setAttribute("duration", `Execution time: ${duration}ms`); - delete sendMessageResult.value.sender - } + // return this sendMessageResult + if(sendMessageResult.isOk()) { + + message.id = sendMessageResult.value.id + + console.log('sendMessageResult', sendMessageResult.value.id) + + if(sendMessageResult.value.sender == undefined || sendMessageResult.value.sender == null) { + + delete sendMessageResult.value.sender + } + + createMessageLocally.then((value) => { + console.log('sendMessageResult', (sendMessageResult as any).value) let clone: MessageTable = { - ...sendMessageResult.value, - id: sendMessageResult.value.id, + ...(sendMessageResult as any).value, + id: (sendMessageResult as any).value.id, $id : message.$id } - + console.log('set update') this.messageLocalDataSourceService.update(message.$id, {...clone, sending: false, roomId: clone.roomId}).then((data)=> { if(data.isOk()) { @@ -187,20 +205,16 @@ export class MessageCreateUseCaseService { console.log(data.error) } }) + }); - return sendMessageResult - } else { - Logger.error('failed to send message to the server', { - error: sendMessageResult.error - }) - await this.messageLocalDataSourceService.update(message.$id, {sending: false, $id: message.$id}) - return err('no connection') - } + return sendMessageResult } else { - Logger.error('failed to insert locally', { - error: createMessageLocally.error.message + Logger.error('failed to send message to the server', { + error: sendMessageResult.error }) + await this.messageLocalDataSourceService.update(message.$id, {sending: false, $id: message.$id}) + return err('no connection') } } else { diff --git a/src/app/core/chat/usecase/message/message-update-by-id-use-case.service.ts b/src/app/core/chat/usecase/message/message-update-by-id-use-case.service.ts index a0f16e2b5..008afeb21 100644 --- a/src/app/core/chat/usecase/message/message-update-by-id-use-case.service.ts +++ b/src/app/core/chat/usecase/message/message-update-by-id-use-case.service.ts @@ -4,6 +4,9 @@ import { ValidateSchema } from 'src/app/services/decorators/validate-schema.deco import { MessageRemoteDataSourceService } from '../../../../module/chat/data/repository/message/message-remote-data-source.service'; import { MessageSocketRepositoryService } from '../../../../module/chat/data/repository/message/message-live-signalr-data-source.service'; import { IMessageSocketRepository } from '../../repository/message/message-socket-repository'; +import { zodSafeValidation } from 'src/app/utils/zodValidation'; +import { Logger } from 'src/app/services/logger/main/service'; +import { TracingType, XTracerAsync } from 'src/app/services/monitoring/opentelemetry/tracer'; const MessageUpdateInputDTOSchema = z.object({ @@ -26,9 +29,23 @@ export class MessageUpdateUseCaseService { public repository: IMessageSocketRepository ) { } - @ValidateSchema(MessageUpdateInputDTOSchema) - execute(input: MessageUpdateInput) { - return this.repository.updateMessage(input); + + @XTracerAsync({name:'MessageUpdateUseCaseService', module:'chat', bugPrint: true, waitNThrow: 5000}) + async execute(input: MessageUpdateInput, tracing?: TracingType) { + console.log('MessageUpdateUseCaseService', input) + const validation = zodSafeValidation(MessageUpdateInputDTOSchema, input) + + if(validation.isOk()) { + + } else { + tracing.hasError('failed to update message, validation failed') + Logger.error('failed to update message, validation failed', { + zodErrorList: validation.error.errors, + data: input + }) + } + + return await this.repository.updateMessage(input); } } diff --git a/src/app/core/chat/usecase/room/room-get-list-use-case.service.ts b/src/app/core/chat/usecase/room/room-get-list-use-case.service.ts index 63031b8c6..2a8c15b0c 100644 --- a/src/app/core/chat/usecase/room/room-get-list-use-case.service.ts +++ b/src/app/core/chat/usecase/room/room-get-list-use-case.service.ts @@ -19,18 +19,20 @@ const CreatedBySchema = z.object({ userPhoto: z.string().nullable()// api check }); +const roomListItemSchema = z.object({ + id: z.string(), + roomName: z.string(), + createdBy: CreatedBySchema, + createdAt: z.string(), + expirationDate: z.string().nullable(), // api check + roomType: z.number(), + messages: MessageEntitySchema.array(), + user1: CreatedBySchema.nullable(), + user2: CreatedBySchema.nullable() +}) + const RoomListItemOutPutDTOSchema = z.object({ - chatRoom: z.object({ - id: z.string(), - roomName: z.string(), - createdBy: CreatedBySchema, - createdAt: z.string(), - expirationDate: z.string().nullable(), // api check - roomType: z.number(), - messages: MessageEntitySchema.array(), - user1: CreatedBySchema.nullable(), - user2: CreatedBySchema.nullable() - }), + chatRoom: roomListItemSchema, joinAt: z.string() }) @@ -43,7 +45,7 @@ export const RoomListOutPutDTOSchema = z.object({ }); export type RoomListItemOutPutDTO = z.infer - +export type RoomListItemSchema = z.infer< typeof roomListItemSchema> export type RoomListOutPutDTO = z.infer @@ -60,7 +62,6 @@ export class GetRoomListUseCaseService { @captureAndReraiseAsync('RoomRepositoryService/list') async execute() { - // console.log('update===============') const result = await this.roomRemoteDataSourceService.getRoomList() const localList = await this.roomLocalDataSourceService.findAll() @@ -90,7 +91,7 @@ export class GetRoomListUseCaseService { // console.log({roomsToDelete, roomsToInsert, roomsToUpdate}) // sometime api return duplicated rooms - const insertedIds = [] + const insertedIds: string[] = [] if(roomsToInsert) { const roomsToInsertEntity = GetRoomListMapper.toDomain(roomsToInsert) @@ -114,7 +115,7 @@ export class GetRoomListUseCaseService { } else { // prevent to insert the same room due to server duplication - if(!insertedIds.find(e => room.id)) { + if(!insertedIds.find(e => room.id == e)) { const createResult = this.roomLocalDataSourceService.insert(room) @@ -122,9 +123,13 @@ export class GetRoomListUseCaseService { createResult.then((result) => { if(result.isErr()) { - console.log('error', result.error) + console.error('error', result.error) } + }).catch(e => { + console.error('error on insert', e); }) + } else { + console.error('server duplication', room.id, insertedIds.toString()) } } diff --git a/src/app/core/chat/usecase/room/room-search-by-name.service.ts b/src/app/core/chat/usecase/room/room-search-by-name.service.ts new file mode 100644 index 000000000..547e4329b --- /dev/null +++ b/src/app/core/chat/usecase/room/room-search-by-name.service.ts @@ -0,0 +1,17 @@ +import { Injectable } from '@angular/core'; +import { IRoomRemoteRepository } from '../../repository/room/room-remote-repository'; + +@Injectable({ + providedIn: 'root' +}) +export class RoomSearchByNameService { + + constructor( + private roomRemoteDataSourceService: IRoomRemoteRepository + ) { } + + async execute(name: string) { + const result = this.roomRemoteDataSourceService.search(name) + + } +} diff --git a/src/app/core/notification/repository/notification-remote-repository.ts b/src/app/core/notification/repository/notification-remote-repository.ts new file mode 100644 index 000000000..e69de29bb diff --git a/src/app/core/notification/use-case/notification-delete-all-use-case.service.ts b/src/app/core/notification/use-case/notification-delete-all-use-case.service.ts new file mode 100644 index 000000000..3ab7b4954 --- /dev/null +++ b/src/app/core/notification/use-case/notification-delete-all-use-case.service.ts @@ -0,0 +1,21 @@ +import { Injectable } from '@angular/core'; +import { RemoteNotificationService } from 'src/app/module/notification/data/datasource/remote-notification.service'; +import { SessionStore } from 'src/app/store/session.service'; +import { z } from 'zod'; + +const NotificationDeleteAllByUserIdSchema = z.any() +export type INotificationDeleteAllByUserId = z.infer + +@Injectable({ + providedIn: 'root' +}) +export class NotificationDeleteAllServiceUseCase { + + constructor( + private RemoteNotificationService:RemoteNotificationService + ) { } + + async execute() { + return this.RemoteNotificationService.notificationDeleteAll(SessionStore.user.UserId) + } +} diff --git a/src/app/core/user/entity/preference.ts b/src/app/core/user/entity/preference.ts new file mode 100644 index 000000000..76cb05c0c --- /dev/null +++ b/src/app/core/user/entity/preference.ts @@ -0,0 +1,6 @@ +export class Preference { + LoginPreference = null + UrlBeforeInactivity= '' + Inactivity= true + PIN = '' +} diff --git a/src/app/core/user/entity/userEntity.ts b/src/app/core/user/entity/userEntity.ts new file mode 100644 index 000000000..38a7250c8 --- /dev/null +++ b/src/app/core/user/entity/userEntity.ts @@ -0,0 +1,139 @@ +// import { z } from "zod"; + +// // Define the schema for the user object +// const UserSchema = z.object({ +// wxUserId: z.number(), +// wxFullName: z.string(), +// wxeMail: z.string(), +// role: z.string(), +// roleId: z.number(), +// userPhoto: z.string(), +// adUserSID: z.string(), +// }); + +// // Define the schema for the main response object +// const UserDataSchema = z.object({ +// user: UserSchema, +// authorization: z.string(), +// refreshToken: z.string(), +// permissions: z.array(z.number()), +// }); + +// export type IUser = z.infer + +// export class UserEntity { + +// wxUserId: number +// wxFullName: string +// wxeMail: string +// role: string +// roleId: number +// userPhoto: string +// adUserSID: string +// authorization: string +// refreshToken: string +// permissions: number[] +// Profile: 'PR' | 'MDGPR'| 'Consultant'| 'SGGPR'| 'Unknown' + +// constructor(input: IUser) { +// Object.assign(this, input) + +// if (input) { +// if (input?.user?.roleId == 100000014) { +// this.Profile = 'PR' +// } else if (input.user.roleId == 100000011) { +// this.Profile = 'MDGPR' +// } else if (input.user.roleId == 99999872) { +// this.Profile = 'Consultant' +// } else if (input.user.roleId == 99999886) { +// this.Profile = 'SGGPR' +// } else { +// this.Profile = 'Unknown' +// } + +// } +// } +// } + + +import { z } from 'zod'; + +const LoginUserResponseSchema = z.object({ + UserId: z.number(), + Authorization: z.string(), + Email: z.string().email(), + FullName: z.string(), + RoleDescription: z.string(), + RoleID: z.number(), + Profile: z.string(), // You can further define the Profile if you have more details + UserPermissions: z.array(z.number()), // Same as above, you can define more details if needed +}); + +type LoginUserResponse = z.infer; + + + +const CalendarInterfaceSchema = z.object({ + CalendarId: z.string(), + CalendarName: z.enum(["Oficial", "Pessoal"]), + CalendarRoleId: z.string(), + Id: z.number(), + OwnerUserId: z.unknown(), // You can define more specifically based on your requirements +}); + +type CalendarInterface = z.infer; + +const UserSessionSchema = z.object({ + UserId: z.number(), + Authorization: z.string(), + Email: z.string().email(), + FullName: z.string(), + RoleDescription: z.string(), + RoleID: z.number(), + Password: z.string(), + RochetChatUserId: z.string(), + Profile: z.enum(['PR', 'MDGPR', 'Consultant', 'SGGPR', 'Unknown']), + LoginPreference: z.enum(['None', 'Password', 'Pin', null]).nullable(), + PIN: z.string(), + Inactivity: z.boolean(), + UrlBeforeInactivity: z.string(), + UserPermissions: z.unknown(), // Again, you can define it more explicitly if needed + UserPhoto: z.string(), + RefreshToken: z.string(), +}); + +type UserSession = z.infer; + +export class UserEntity { + + wxUserId: number + wxFullName: string + wxeMail: string + role: string + roleId: number + userPhoto: string + adUserSID: string + authorization: string + refreshToken: string + permissions: number[] + Profile: 'PR' | 'MDGPR'| 'Consultant'| 'SGGPR'| 'Unknown' + + constructor(input: any) { + Object.assign(this, input) + + if (input) { + if (input?.user?.roleId == 100000014) { + this.Profile = 'PR' + } else if (input.user.roleId == 100000011) { + this.Profile = 'MDGPR' + } else if (input.user.roleId == 99999872) { + this.Profile = 'Consultant' + } else if (input.user.roleId == 99999886) { + this.Profile = 'SGGPR' + } else { + this.Profile = 'Unknown' + } + + } + } +} diff --git a/src/app/core/user/mapper/user-login.ts b/src/app/core/user/mapper/user-login.ts new file mode 100644 index 000000000..6624fc437 --- /dev/null +++ b/src/app/core/user/mapper/user-login.ts @@ -0,0 +1,19 @@ +import { UserLoginOutputResponse } from "../repository/user-remote-repository"; +import { UserLoginOutput } from "../use-case/user-login-use-case.service"; + +export class UserLoginMapper{ + static toDomainData(input: UserLoginOutputResponse): UserLoginOutput { + return { + RefreshToken: input.data.refreshToken, + Authorization: input.data.authorization, + Email: input.data.user.wxeMail, + FullName: input.data.user.wxFullName, + RoleDescription: input.data.user.role, + RoleID: input.data.user.roleId, + UserId: input.data.user.wxUserId, + UserPermissions: input.data.permissions, + Profile: '', + UserPhoto: input.data.user?.userPhoto + } + } +} \ No newline at end of file diff --git a/src/app/core/user/repository/user-remote-repository.ts b/src/app/core/user/repository/user-remote-repository.ts new file mode 100644 index 000000000..ec2d7dad4 --- /dev/null +++ b/src/app/core/user/repository/user-remote-repository.ts @@ -0,0 +1,58 @@ +import { HttpErrorResponse } from "@angular/common/http"; +import { Result } from "neverthrow"; +import { HttpResult } from "src/app/infra/http/type"; +import { UserLoginInput } from "../use-case/user-login-use-case.service"; +import { z } from "zod"; + +const UserRepositoryLoginParams = z.object({ + Auth: z.string(), + ChannelId: z.number() +}) + + +// Define the schema for the user object +const UserSchema = z.object({ + wxUserId: z.number(), + wxFullName: z.string(), + wxeMail: z.string(), + role: z.string(), + roleId: z.number(), + userPhoto: z.string(), + adUserSID: z.string(), +}); + +// Define the schema for the main response object +const UserLoginOutputSchema = z.object({ + user: UserSchema, + authorization: z.string(), + refreshToken: z.string(), + permissions: z.array(z.number()), +}); + +// Define the main schema for the response +const LoginUserResponseSchema = z.object({ + success: z.boolean(), + message: z.nullable(z.string()), // Message can be null + data: UserLoginOutputSchema, +}); + + + +export type UserLoginOutputResponse = z.infer + +const UserRefreshTokenInputSchema = z.object({ + authorization: z.string(), + refreshToken: z.string(), + channelId: z.number() +}) + +export type UserRefreshTokenInputDTO = z.infer + + + +export type IUserRepositoryLoginParams = z.infer +export abstract class IUserRemoteRepository { + abstract login(input: IUserRepositoryLoginParams): Promise, HttpErrorResponse>> + abstract logout(): Promise, HttpErrorResponse>> + abstract refreshToken(input:UserRefreshTokenInputDTO): Promise, HttpErrorResponse>> +} diff --git a/src/app/core/user/use-case/user-log-out-use-case.service.ts b/src/app/core/user/use-case/user-log-out-use-case.service.ts new file mode 100644 index 000000000..f102cad89 --- /dev/null +++ b/src/app/core/user/use-case/user-log-out-use-case.service.ts @@ -0,0 +1,55 @@ +import { Injectable } from '@angular/core'; +import { IUserRemoteRepository } from '../repository/user-remote-repository'; +import { XTracerAsync } from 'src/app/services/monitoring/opentelemetry/tracer'; +import { SessionStore } from 'src/app/store/session.service'; +import { Router } from '@angular/router'; +import { environment } from 'src/environments/environment'; +import { NotificationsService } from 'src/app/services/notifications.service'; + +@Injectable({ + providedIn: 'root' +}) +export class UserLogOutUseCaseService { + + constructor( + private userRemoteRepository: IUserRemoteRepository, + private router: Router, + private notificationService: NotificationsService, + ) { } + + @XTracerAsync({name:'UserLogOutUseCaseService', module:'user', bugPrint: true}) + async execute() { + let logoutOut = false + + let subscription = this.router.events.subscribe((val) => { + logoutOut = true + }); + + const result = await this.userRemoteRepository.logout() + + SessionStore.setInativity(false) + SessionStore.setUrlBeforeInactivity(this.router.url); + logoutOut == false + + if (environment.production) { + window.location.pathname = '/auth' + this.notificationService.DeletePostToken() + subscription.unsubscribe() + } else { + const pathBeforeGoOut = window.location.pathname + this.router.navigateByUrl('/auth', { replaceUrl: true }); + this.notificationService.DeletePostToken() + + setTimeout(() => { + if (logoutOut == false || pathBeforeGoOut == window.location.pathname) { + window.location.pathname = '/auth' + this.notificationService.DeletePostToken() + } else { + + } + subscription.unsubscribe() + }, 500) + } + + } +} diff --git a/src/app/core/user/use-case/user-login-use-case.service.ts b/src/app/core/user/use-case/user-login-use-case.service.ts new file mode 100644 index 000000000..92941cd30 --- /dev/null +++ b/src/app/core/user/use-case/user-login-use-case.service.ts @@ -0,0 +1,104 @@ +import { Injectable } from '@angular/core'; +import { z, ZodError, ZodSchema } from 'zod'; +import { IUserRemoteRepository } from '../repository/user-remote-repository'; +import { XTracerAsync, TracingType } from 'src/app/services/monitoring/opentelemetry/tracer'; +import { zodSafeValidation } from 'src/app/utils/zodValidation'; +import { Platform } from '@ionic/angular'; +import { AESEncrypt } from 'src/app/services/aesencrypt.service'; +import { UserLoginMapper } from '../mapper/user-login'; +import { UserSession } from 'src/app/models/user.model'; +import { SessionStore } from 'src/app/store/session.service'; +import { err, ok, Result } from 'neverthrow'; +import { error } from '../../../services/Either/index'; + +const UserLoginInputSchema = z.object({ + username: z.string(), + password: z.string() +}) + +export type UserLoginInput = z.infer + + + +// Define the schema for the main response object +const UserLoginOutputSchema = z.object({ + UserId: z.number(), + Authorization: z.string(), + RefreshToken: z.string(), + Email: z.string().email(), + FullName: z.string(), + RoleDescription: z.string(), + RoleID: z.number(), + Profile: z.string(), // You can further define the Profile if you have more details + UserPermissions: z.array(z.number()), // Same as above, you can define more details if needed + UserPhoto: z.string().optional() +}); + + + +export type UserLoginOutput = z.infer + +export enum LoginError { + userNotFound = 401, + +} + +@Injectable({ + providedIn: 'root' +}) +export class UserLoginUseCaseService { + + constructor( + private userRemoteRepository: IUserRemoteRepository, + private aesencrypt: AESEncrypt, + private platform: Platform + ) { } + + @XTracerAsync({name:'UserLoginUseCaseService', module:'user', bugPrint: true}) + async execute(input: UserLoginInput, tracing?: TracingType): Promise>> { + const validation = zodSafeValidation(UserLoginInputSchema, input) + + if(validation.isOk()) { + + let channelId; + if ( this.platform.is('desktop') || this.platform.is("mobileweb")) { + channelId = 2 + } else { + channelId = 1 + } + + const auth = btoa(input.username + ':' + this.aesencrypt.encrypt(input.password, input.username)) + + const result = await this.userRemoteRepository.login({ + Auth: auth, + ChannelId: channelId + }) + + if(result.isOk() && result.value.data.data) { + + const data = UserLoginMapper.toDomainData(result.value.data); + const session: UserSession = Object.assign(SessionStore.user, data); + SessionStore.reset(session); + + return ok(data) + + } else if (result.isOk() && !result.value.data.data) { + return err(LoginError.userNotFound) + } + + if(result.isErr() && result.error.status) { + return err(result.error.status as LoginError) + } + + } else { + tracing.setAttribute('parameter error','true') + // Logger.error('failed to send message doe to invalid attachment', { + // zodErrorList: validation.error.errors, + // data: data + // }) + + return validation + } + + } +} diff --git a/src/app/core/user/use-case/user-refresh-token.service.ts b/src/app/core/user/use-case/user-refresh-token.service.ts new file mode 100644 index 000000000..7c26c6597 --- /dev/null +++ b/src/app/core/user/use-case/user-refresh-token.service.ts @@ -0,0 +1,34 @@ +import { Injectable } from '@angular/core'; +import { z } from 'zod'; +import { IUserRemoteRepository } from '../repository/user-remote-repository'; +import { SessionStore } from 'src/app/store/session.service'; +import { Platform } from '@ionic/angular'; +import { XTracerAsync } from 'src/app/services/monitoring/opentelemetry/tracer'; + + +@Injectable({ + providedIn: 'root' +}) +export class UserRefreshTokenService { + + constructor( + private userRemoteRepository: IUserRemoteRepository, + private platform: Platform + ) { } + + @XTracerAsync({name:'UserRefreshTokenService', module:'user', bugPrint: true}) + async execute() { + let channelId; + if ( this.platform.is('desktop') || this.platform.is("mobileweb")){ + channelId = 2 + } else { + channelId = 1 + } + + return await this.userRemoteRepository.refreshToken({ + authorization: SessionStore.user.Authorization, + refreshToken: SessionStore.user.RefreshToken, + channelId + }) + } +} diff --git a/src/app/guards/auth.guard.ts b/src/app/guards/auth.guard.ts index 682c75262..d8fb26030 100644 --- a/src/app/guards/auth.guard.ts +++ b/src/app/guards/auth.guard.ts @@ -3,18 +3,17 @@ import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Rout import { Observable } from 'rxjs'; import { PermissionService } from '../services/permission.service'; import { SessionStore } from '../store/session.service'; -import { RouteService } from 'src/app/services/route.service' -import { FirstEnterService } from 'src/app/services/first-enter.service' -import { AlertController, Platform } from '@ionic/angular'; + @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { + constructor( private router:Router, public p: PermissionService, - ){} + ) {} canActivate( route: ActivatedRouteSnapshot, @@ -68,12 +67,13 @@ export class AuthGuard implements CanActivate { return false } } else if (pathname.startsWith('/home/events')) { - if(SessionStore?.user?.OwnerCalendars.length >= 1 || this.p.userPermission([this.p.permissionList.Gabinete.access])) { - return true - } else { - this.router.navigate(['/login']); - return false - } + return true + // if(SessionStore?.user?.OwnerCalendars.length >= 1 || this.p.userPermission([this.p.permissionList.Gabinete.access])) { + // return true + // } else { + // this.router.navigate(['/login']); + // return false + // } } else if (pathname == '/') { this.router.navigate(['/login']); return false diff --git a/src/app/guards/inactivity.guard.ts b/src/app/guards/inactivity.guard.ts index ec340857d..0d6dece06 100644 --- a/src/app/guards/inactivity.guard.ts +++ b/src/app/guards/inactivity.guard.ts @@ -29,7 +29,8 @@ export class InactivityGuard implements CanActivate { if(this.p.userPermission(this.p.permissionList.Agenda.access) || this.p.userPermission(this.p.permissionList.Gabinete.access)) { //When user has got access to Agenda but does not have their own calendar, goes to Agenda - if(this.p.userPermission(this.p.permissionList.Agenda.access) && SessionStore?.user?.OwnerCalendars.length == 0){ + //if(this.p.userPermission(this.p.permissionList.Agenda.access) && SessionStore?.user?.OwnerCalendars.length == 0){ + if(this.p.userPermission(this.p.permissionList.Agenda.access)){ this.router.navigate(['/home/agenda']); } else{ @@ -79,7 +80,8 @@ export class InactivityGuard implements CanActivate { if((SessionStore?.user?.Inactivity)) { if(this.p.userPermission(this.p.permissionList.Agenda.access) || this.p.userPermission(this.p.permissionList.Gabinete.access)){ //When user has got access to Agenda but does not have their own calendar, goes to Agenda - if(this.p.userPermission(this.p.permissionList.Agenda.access) && SessionStore?.user?.OwnerCalendars.length == 0) { + //if(this.p.userPermission(this.p.permissionList.Agenda.access) && SessionStore?.user?.OwnerCalendars.length == 0) { + if(this.p.userPermission(this.p.permissionList.Agenda.access)) { this.router.navigate(['/home/agenda']); } else{ diff --git a/src/app/home/home.page.html b/src/app/home/home.page.html index 656f49cf6..b5f4dd11a 100644 --- a/src/app/home/home.page.html +++ b/src/app/home/home.page.html @@ -6,8 +6,10 @@ - - + + + diff --git a/src/app/home/home.page.ts b/src/app/home/home.page.ts index 2192335ca..f2631edc0 100644 --- a/src/app/home/home.page.ts +++ b/src/app/home/home.page.ts @@ -229,9 +229,9 @@ export class HomePage implements OnInit { 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.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'); diff --git a/src/app/index/index-routing.module.ts b/src/app/index/index-routing.module.ts index d3b578966..68b3e2c9e 100644 --- a/src/app/index/index-routing.module.ts +++ b/src/app/index/index-routing.module.ts @@ -7,12 +7,7 @@ const routes: Routes = [ { path: '', component: IndexPage, - /* canActivate: [IndexGuard], */ children: [ - /*{ - path: '', - loadChildren: ()=> import('../pages/welcome/welcome.module').then(m => m.WelcomePageModule) - }, */ { path: '', loadChildren: ()=> import('../pages/login/login.module').then(m => m.LoginPageModule), diff --git a/src/app/infra/database/dexie/instance/chat/service.ts b/src/app/infra/database/dexie/instance/chat/service.ts index 173f833bb..c6c3e321c 100644 --- a/src/app/infra/database/dexie/instance/chat/service.ts +++ b/src/app/infra/database/dexie/instance/chat/service.ts @@ -1,22 +1,22 @@ import { Dexie } from 'Dexie'; -import { DexieMessageTable, messageTableColumn, MessageTable } from 'src/app/infra/database/dexie/instance/chat/schema/message'; +import { DexieMessageTable, messageTableColumn } from 'src/app/infra/database/dexie/instance/chat/schema/message'; import { DexieMembersTableSchema, MemberTableColumn } from 'src/app/infra/database/dexie/instance/chat/schema/members'; import { DexieRoomsTable, RoomTableColumn } from 'src/app/infra/database/dexie/instance/chat/schema/room'; import { DexieTypingsTable, TypingTableColumn } from 'src/app/infra/database/dexie/instance/chat/schema/typing'; import { MessageEntity } from 'src/app/core/chat/entity/message'; import { AttachmentTableColumn, DexieAttachmentsTableSchema } from 'src/app/infra/database/dexie/instance/chat/schema/attachment'; -import { DexieDistributionTable, DistributionTable, DistributionTableColumn } from './schema/destribution'; +import { DexieDistributionTable, DistributionTableColumn } from './schema/destribution'; import { BoldTableColumn, DexieBoldTable } from './schema/bold'; -import { DexieUserPhotoTable, UserPhotoTable, UserPhotoTableColumn } from './schema/user-foto'; -// import FDBFactory from 'fake-indexeddb/lib/FDBFactory'; -// import FDBKeyRange from 'fake-indexeddb/lib/FDBKeyRange'; +import { DexieUserPhotoTable, UserPhotoTableColumn } from './schema/user-foto'; +import FDBFactory from 'fake-indexeddb/lib/FDBFactory'; +import FDBKeyRange from 'fake-indexeddb/lib/FDBKeyRange'; // Database declaration (move this to its own module also) -export const chatDatabase = new Dexie('chat-database-v3',{ -// indexedDB: new FDBFactory, -// IDBKeyRange: FDBKeyRange, // Mocking IDBKeyRange +export const chatDatabase = new Dexie('chat-database-v4',{ + //indexedDB: new FDBFactory, + //IDBKeyRange: FDBKeyRange, // Mocking IDBKeyRange }) as Dexie & { message: DexieMessageTable, members: DexieMembersTableSchema, diff --git a/src/app/infra/http/http.service.ts b/src/app/infra/http/http.service.ts index aaf1f8616..0b9336bff 100644 --- a/src/app/infra/http/http.service.ts +++ b/src/app/infra/http/http.service.ts @@ -48,7 +48,7 @@ export class HttpService { const httpOptions = { params: httpParams, - headers: options?.headers || new HttpHeaders(), + headers: options?.headers as any || new HttpHeaders(), responseType: options?.responseType || 'json' as any, }; diff --git a/src/app/interceptors/metter.interceptor.ts b/src/app/infra/monitoring/interceptors/metter.interceptor.ts similarity index 93% rename from src/app/interceptors/metter.interceptor.ts rename to src/app/infra/monitoring/interceptors/metter.interceptor.ts index c5e951afe..d5ac9e305 100644 --- a/src/app/interceptors/metter.interceptor.ts +++ b/src/app/infra/monitoring/interceptors/metter.interceptor.ts @@ -2,7 +2,7 @@ import { Injectable } from '@angular/core'; import { HTTP_INTERCEPTORS, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; -import { meter, RequestCounter } from '../services/monitoring/opentelemetry/matrix'; +import { meter, RequestCounter } from '../../../services/monitoring/opentelemetry/matrix'; @Injectable() diff --git a/src/app/interceptors/token.interceptors.ts b/src/app/infra/monitoring/interceptors/token.interceptors.ts similarity index 66% rename from src/app/interceptors/token.interceptors.ts rename to src/app/infra/monitoring/interceptors/token.interceptors.ts index 2d8027338..4c91bc67e 100644 --- a/src/app/interceptors/token.interceptors.ts +++ b/src/app/infra/monitoring/interceptors/token.interceptors.ts @@ -10,10 +10,14 @@ import { } from "@angular/common/http"; import { Observable, throwError, BehaviorSubject, of } from "rxjs"; import { catchError, filter, take, switchMap, tap } from "rxjs/operators"; -import { SessionStore } from '../store/session.service'; +import { SessionStore } from '../../../store/session.service'; import { environment } from "src/environments/environment"; import { Router } from "@angular/router"; import { HttpErrorHandle } from 'src/app/services/http-error-handle.service'; +import { Platform } from '@ionic/angular'; +import { UserLoginOutputResponse } from "../../../core/user/repository/user-remote-repository"; +import { UserLoginMapper } from "../../../core/user/mapper/user-login"; +import { UserSession } from "../../../models/user.model"; @Injectable() export class TokenInterceptor implements HttpInterceptor { @@ -24,7 +28,11 @@ export class TokenInterceptor implements HttpInterceptor { private excludedDomains = [ 'Login', environment.apiChatUrl, 'http://localhost:8019']; // Add the domains you want to exclude - constructor(private http: HttpClient, private router: Router,private httpErrorHandle: HttpErrorHandle,) { } + constructor( + private http: HttpClient, + private router: Router, + private httpErrorHandle: HttpErrorHandle, + private platform: Platform) { } intercept( @@ -44,7 +52,11 @@ export class TokenInterceptor implements HttpInterceptor { catchError((error) => { console.log('interceptor ',error) - if (error instanceof HttpErrorResponse && error.status === 401) { + if(error.url.includes('/Users/RefreshToken') && error.status === 401) { + console.log("refresh token error11",error) + return throwError(error); + } + else if (error instanceof HttpErrorResponse && error.status === 401) { return this.handle401Error(request, next); } else if (error.url.includes('https://gdapi-dev.dyndns.info/stage/api/v2') && error.status === 0){ return this.handle401Error(request, next); @@ -78,10 +90,10 @@ export class TokenInterceptor implements HttpInterceptor { this.refreshTokenSubject.next(null); return this.refreshToken().pipe( - switchMap((token: any) => { + switchMap((data: UserLoginOutputResponse) => { this.isRefreshing = false; - this.refreshTokenSubject.next(token.Authorization); - return next.handle(this.addToken(request, token.Authorization)); + this.refreshTokenSubject.next(data?.data?.authorization); + return next.handle(this.addToken(request, data?.data?.authorization)); }) ); } else { @@ -99,23 +111,33 @@ export class TokenInterceptor implements HttpInterceptor { //this method refresh token is declared here temporary beacouse a circular error refreshToken() { + let channelId; + if ( this.platform.is('desktop') || this.platform.is("mobileweb")){ + channelId = 2 + } else { + channelId = 1 + } return this.http - .put(environment.apiURL + "UserAuthentication/RefreshToken", { + .post('https://gdapi-dev.dyndns.info/stage/api/v2/Users/RefreshToken', { + authorization: SessionStore.user.Authorization, refreshToken: SessionStore.user.RefreshToken, + channelId },) .pipe( - tap((tokens) => { - console.log(tokens) - SessionStore.user.Authorization = tokens.Authorization; - SessionStore.user.RefreshToken = tokens.refreshToken; - SessionStore.save(); + tap((data) => { + + SessionStore.user.Authorization = data.data.authorization; + SessionStore.user.RefreshToken = data.data.refreshToken; + //const userData = UserLoginMapper.toDomainData(data) + //const session: UserSession = Object.assign(SessionStore.user, userData) + //SessionStore.reset(session)ta }), catchError((error) => { - console.log(error) - SessionStore.user.Authorization = SessionStore.user.Authorization; - SessionStore.user.RefreshToken = SessionStore.user.RefreshToken; + console.log("refresh token error",error) + // SessionStore.user.Authorization = SessionStore.user.Authorization; + // SessionStore.user.RefreshToken = SessionStore.user.RefreshToken; SessionStore.setInativity(false) /* SessionStore.setUrlBeforeInactivity(this.router.url); */ diff --git a/src/app/interceptors/chatToken.interceptor.ts b/src/app/interceptors/chatToken.interceptor.ts deleted file mode 100644 index 2185ce850..000000000 --- a/src/app/interceptors/chatToken.interceptor.ts +++ /dev/null @@ -1,179 +0,0 @@ -import { Injectable } from '@angular/core'; -import { - HttpInterceptor, - HttpRequest, - HttpHandler, - HttpEvent, - HttpErrorResponse, - HTTP_INTERCEPTORS, - HttpHeaders, -} from '@angular/common/http'; -import { Observable, throwError, BehaviorSubject } from 'rxjs'; -import { catchError, switchMap, filter, take } from 'rxjs/operators'; -import { HttpClient } from '@angular/common/http'; -import { Router } from '@angular/router'; -import { SessionStore } from '../store/session.service'; -import { environment } from "src/environments/environment"; -import { PermissionService } from '../services/permission.service'; -import { NetworkServiceService, ConnectionStatus } from 'src/app/services/network-service.service'; -// import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'; - -@Injectable() -export class ChatTokenInterceptor implements HttpInterceptor { - private isRefreshing = false; - headers: HttpHeaders; - options: any; - private refreshChatTokenSubject: BehaviorSubject = new BehaviorSubject( - null - ); - - private excludedDomains = ['Login',environment.apiURL, 'http://localhost:8019'];// Add other domains as needed - - constructor(private http: HttpClient, private router: Router, private p: PermissionService, private NetworkServiceService: NetworkServiceService) { } - - intercept( - request: HttpRequest, - next: HttpHandler - ): Observable> { - if (this.shouldExcludeDomain(request)) { - return next.handle(request); - } - - if (SessionStore.user.Authorization) { - request = this.addToken(request, SessionStore.user.Authorization); - } - - return next.handle(request).pipe( - catchError((error) => { - if (error instanceof HttpErrorResponse && error.status === 401) { - return this.handle401Error(request, next); - } else { - return throwError(error); - } - }) - ); - } - - private shouldExcludeDomain(request: HttpRequest): boolean { - const url = request.url.toLowerCase(); - return this.excludedDomains.some((domain) => url.includes(domain.toLowerCase())); - } - - private handle401Error( - request: HttpRequest, - next: HttpHandler - ): Observable> { - if (!this.isRefreshing) { - this.isRefreshing = true; - this.refreshChatTokenSubject.next(null); - - return this.refreshToken().pipe( - switchMap((token: any) => { - this.isRefreshing = false; - - let data = { - status: token['status'], - data: { - userId: token['data'].userId, - authToken: token['data'].authToken - } - } - SessionStore.user.ChatData = data - SessionStore.save() - /* this.setheader() */ - - - - this.refreshChatTokenSubject.next(token.Authorization); - return next.handle(this.addToken(request, token.Authorization)); - }) - ); - } else { - return this.refreshChatTokenSubject.pipe( - filter((token) => token != null), - take(1), - switchMap((jwt) => { - return next.handle(this.addToken(request, jwt)); - }) - ); - } - } - - private addToken(request: HttpRequest, token: string) { - let headers = new HttpHeaders(); - - try { - - headers = headers.set('X-User-Id', SessionStore?.user?.ChatData?.data?.userId); - headers = headers.set('X-Auth-Token', SessionStore?.user?.ChatData?.data.authToken); - - return request.clone({ - setHeaders: { - Authorization: `Bearer ${token}`, - ...headers.keys().reduce((acc, key) => ({ ...acc, [key]: headers.get(key) }), {}), - }, - }) - } catch (error) { - - - return request.clone({ - setHeaders: { - Authorization: `Bearer ${token}`, - }, - }) - } - } - - /* private addToken(request: HttpRequest, token: string) { - return request.clone({ - setHeaders: { - Authorization: `Bearer ${token}`, - }, - }); - } */ - - private refreshToken(): Observable { - return this.http - .get(environment.apiURL + 'UserAuthentication/RegenereChatToken', { - /* refreshToken: SessionStore.user.RefreshToken, */ - }) - .pipe( - catchError((error) => { - // Handle token refresh failure - console.log('ChatToken refresh failed:', error); - return throwError(error); - }) - ); - } - - - - setheader() { - try { - - if (this.p.userPermission(this.p.permissionList.Chat.access) && SessionStore.user.ChatData) { - this.headers = new HttpHeaders();; - - if (this.p.userPermission(this.p.permissionList.Chat.access)) { - // - this.headers = this.headers.set('X-User-Id', SessionStore.user.ChatData.data.userId); - this.headers = this.headers.set('X-Auth-Token', SessionStore.user.ChatData.data.authToken); - this.options = { - headers: this.headers, - }; - - } - } - } catch (error) { - - } - } -} - - - -export const chatTokenInterceptor = { - provide: HTTP_INTERCEPTORS, - useClass: ChatTokenInterceptor, - multi: true -}; diff --git a/src/app/modals/create-process/create-process.page.ts b/src/app/modals/create-process/create-process.page.ts index 9f1754db3..7d11862f3 100644 --- a/src/app/modals/create-process/create-process.page.ts +++ b/src/app/modals/create-process/create-process.page.ts @@ -9,7 +9,7 @@ import { DiscartExpedientModalPage } from 'src/app/pages/gabinete-digital/discar import { ExpedienteDetailPage } from 'src/app/pages/gabinete-digital/expediente/expediente-detail/expediente-detail.page'; import { SearchList } from 'src/app/models/search-document'; import { SearchPage } from 'src/app/pages/search/search.page'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { AttendeesPageModal } from 'src/app/pages/events/attendees/attendees.page'; import { ToastService } from 'src/app/services/toast.service'; import { FormControl, FormGroup, Validators } from '@angular/forms'; @@ -85,7 +85,7 @@ export class CreateProcessPage implements OnInit { documents: SearchList[] = []; - loggeduser: LoginUserRespose; + loggeduser: UserSession; toppings = new FormControl(); @@ -311,7 +311,8 @@ export class CreateProcessPage implements OnInit { UserEmail: this.loggeduser.Email, UsersSelected: attendees, DispatchFolder: this.dispatchFolder, - AttachmentList: docs + AttachmentList: docs, + dataFields: {} } try { @@ -337,7 +338,8 @@ export class CreateProcessPage implements OnInit { UserEmail: this.loggeduser.Email, UsersSelected: attendees, DispatchFolder: this.dispatchFolder, - AttachmentList: docs + AttachmentList: docs, + dataFields: { a: 1} } try { @@ -362,7 +364,8 @@ export class CreateProcessPage implements OnInit { UserEmail: this.loggeduser.Email, UsersSelected: attendees, DispatchFolder: this.dispatchFolder, - AttachmentList: docs + AttachmentList: docs, + dataFields: {} } try { @@ -395,7 +398,8 @@ export class CreateProcessPage implements OnInit { UserEmail: this.loggeduser.Email, UsersSelected: attendees, DispatchFolder: this.dispatchFolder, - AttachmentList: docs + AttachmentList: docs, + dataFields: {} } try { @@ -425,7 +429,8 @@ export class CreateProcessPage implements OnInit { UserEmail: this.loggeduser.Email, UsersSelected: attendees, DispatchFolder: this.dispatchFolder, - AttachmentList: docs + AttachmentList: docs, + dataFields: {} } /* if (this.postData.DispatchFolder.Message) { */ @@ -456,7 +461,8 @@ export class CreateProcessPage implements OnInit { UserEmail: this.loggeduser.Email, UsersSelected: attendees, DispatchFolder: this.dispatchFolder, - AttachmentList: docs + AttachmentList: docs, + dataFields: {} } try { @@ -488,7 +494,8 @@ export class CreateProcessPage implements OnInit { UserEmail: this.loggeduser.Email, UsersSelected: attendees, DispatchFolder: this.dispatchFolder, - AttachmentList: docs + AttachmentList: docs, + dataFields: {} } try { diff --git a/src/app/modals/document-set-up-meeting/document-set-up-meeting.page.ts b/src/app/modals/document-set-up-meeting/document-set-up-meeting.page.ts index 9dbc6ce48..a96135c8d 100644 --- a/src/app/modals/document-set-up-meeting/document-set-up-meeting.page.ts +++ b/src/app/modals/document-set-up-meeting/document-set-up-meeting.page.ts @@ -5,7 +5,7 @@ import { Event } from 'src/app/models/event.model' import { EventPerson } from 'src/app/models/eventperson.model'; import { SearchPage } from 'src/app/pages/search/search.page'; import { SearchDocumentDetails, SearchFolderDetails, SearchList } from 'src/app/models/search-document'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { AuthService } from 'src/app/services/auth.service'; import { AttendeesPageModal } from 'src/app/pages/events/attendees/attendees.page'; import { ToastService } from 'src/app/services/toast.service'; @@ -92,7 +92,7 @@ export class DocumentSetUpMeetingPage implements OnInit { formLocationSatus: boolean = false; showAttendees = false; - loggeduser: LoginUserRespose; + loggeduser: UserSession; emptyTextDescription = "Selecionar intervenientes"; document: SearchFolderDetails | SearchDocumentDetails | any; diff --git a/src/app/modals/profile/edit-profile/edit-profile.page.html b/src/app/modals/profile/edit-profile/edit-profile.page.html index 9808fd404..8987f351c 100644 --- a/src/app/modals/profile/edit-profile/edit-profile.page.html +++ b/src/app/modals/profile/edit-profile/edit-profile.page.html @@ -125,7 +125,7 @@ - + diff --git a/src/app/modals/profile/profile.module.ts b/src/app/modals/profile/profile.module.ts index f87f01cb6..1d6a69d2f 100644 --- a/src/app/modals/profile/profile.module.ts +++ b/src/app/modals/profile/profile.module.ts @@ -7,13 +7,16 @@ import { IonicModule } from '@ionic/angular'; import { ProfilePageRoutingModule } from './profile-routing.module'; import { ProfilePage } from './profile.page'; +import { UserModule } from 'src/app/module/user/user.module'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, - ProfilePageRoutingModule + ProfilePageRoutingModule, + // + UserModule ], declarations: [ProfilePage] }) diff --git a/src/app/modals/profile/profile.page.html b/src/app/modals/profile/profile.page.html index 71b1cbc25..808c0bd54 100644 --- a/src/app/modals/profile/profile.page.html +++ b/src/app/modals/profile/profile.page.html @@ -85,19 +85,23 @@
+ + +
-
-
+
diff --git a/src/app/modals/profile/profile.page.scss b/src/app/modals/profile/profile.page.scss index 4a31f6f60..4cbc5d718 100644 --- a/src/app/modals/profile/profile.page.scss +++ b/src/app/modals/profile/profile.page.scss @@ -77,6 +77,7 @@ } .profile-content { padding: 20px 20px; + padding-bottom: 5px; //color: var(--profile-text-color) !important; } diff --git a/src/app/modals/profile/profile.page.ts b/src/app/modals/profile/profile.page.ts index 591477aa5..b1d06caa8 100644 --- a/src/app/modals/profile/profile.page.ts +++ b/src/app/modals/profile/profile.page.ts @@ -4,7 +4,6 @@ import { AnimationController, ModalController } from '@ionic/angular'; import { AuthService } from 'src/app/services/auth.service'; import { EditProfilePage } from './edit-profile/edit-profile.page'; import { StorageService } from '../../services/storage.service'; -import { NotificationsService } from '../../services/notifications.service'; import { SessionStore } from 'src/app/store/session.service'; import { ThemeService } from 'src/app/services/theme.service' import { environment } from 'src/environments/environment'; @@ -19,6 +18,8 @@ import { NotificationTable } from 'src/app/module/notification/data/infra/db/not import { isHttpError } from 'src/app/services/http.service'; import { UserRepositoryService } from 'src/app/module/user/data/user-repository.service'; import { UserProfilePicture } from 'src/app/module/user/data/datasource/user-local-repository.service'; +import { UserService } from 'src/app/module/user/domain/user.service' +import { NotificationService } from 'src/app/module/notification/domain/notification.service' @Component({ selector: 'app-profile', @@ -61,7 +62,7 @@ export class ProfilePage implements OnInit { private router: Router, private zone: NgZone, public ThemeService: ThemeService, - private notificationService: NotificationsService, + private NotificationService: NotificationService, private processesService: ProcessesService, private storageService: StorageService, public NotificationHolderService: NotificationHolderService, @@ -69,7 +70,8 @@ export class ProfilePage implements OnInit { private agendaDataRepository: AgendaDataRepositoryService, private toastService: ToastService, private notificationRepositoryService: NotificationRepositoryService, - private UserRepositoryService: UserRepositoryService + private UserRepositoryService: UserRepositoryService, + private UserService:UserService, ) { this.profilePictureSubject = this.UserRepositoryService.getProfilePictureLive() as any @@ -350,29 +352,7 @@ export class ProfilePage implements OnInit { } logout() { - this.authservice.logoutUser(); - SessionStore.setInativity(false) - SessionStore.setUrlBeforeInactivity(this.router.url); - this.logoutOut == false - - if (environment.production) { - window.location.pathname = '/auth' - this.notificationService.DeletePostToken() - } else { - const pathBeforeGoOut = window.location.pathname - this.router.navigateByUrl('/auth', { replaceUrl: true }); - this.notificationService.DeletePostToken() - - setTimeout(() => { - if (this.logoutOut == false || pathBeforeGoOut == window.location.pathname) { - window.location.pathname = '/auth' - this.notificationService.DeletePostToken() - } else { - - } - }, 500) - } - + this.UserService.logout(); } async editProfile() { @@ -436,4 +416,11 @@ export class ProfilePage implements OnInit { this.deleteNotification(item); } + + async deleteAllNotification() { + console.log('nice job') + await this.NotificationService.deleteAllNotificationByUserId() + this.notificationRepositoryService.init() + + } } diff --git a/src/app/models/despacho.model.ts b/src/app/models/despacho.model.ts index b21e2e1c8..76d2e0c59 100644 --- a/src/app/models/despacho.model.ts +++ b/src/app/models/despacho.model.ts @@ -15,4 +15,5 @@ export class Despacho{ SourceId: string }[], } -} \ No newline at end of file + dataFields: Object +} diff --git a/src/app/models/permission/agenda-permission.ts b/src/app/models/permission/agenda-permission.ts index 1129b6bd6..a4abe000b 100644 --- a/src/app/models/permission/agenda-permission.ts +++ b/src/app/models/permission/agenda-permission.ts @@ -6,13 +6,16 @@ export class AgendaPermission{ constructor() { if(SessionStore.exist) { - for (let calendar of SessionStore?.user?.OwnerCalendars) { - this.hasOwnCalendar = true - } + // for (let calendar of SessionStore?.user?.OwnerCalendars) { + // this.hasOwnCalendar = true + // } - for (let sharedCalendar of SessionStore?.user?.SharedCalendars) { - this.hasSharedCalendar = true - } + // for (let sharedCalendar of SessionStore?.user?.SharedCalendars) { + // this.hasSharedCalendar = true + // } + + this.hasOwnCalendar = true + this.hasSharedCalendar = true } } get access () { diff --git a/src/app/models/user.model.ts b/src/app/models/user.model.ts index 0a7fd6fb1..cdb78937f 100644 --- a/src/app/models/user.model.ts +++ b/src/app/models/user.model.ts @@ -6,41 +6,6 @@ export class UserForm { } -export class LoginUserRespose { - BasicAuthKey: string; - UserId: number; - Authorization: string; - ChatData: { - status: string, - data: { - userId: string, - authToken: string - } - } - Email: string - FullName: string - OwnerCalendars: { - CalendarId: string - CalendarName: "Oficial" | "Pessoal"; - CalendarRoleId: string; - Id: number; - }[] - RoleDescription: string - RoleID: number - SharedCalendars: { - CalendarId: string - CalendarName: "Oficial" | "Pessoal"; - CalendarRoleId: string; - Id: number; - OwnerUserId: string; - TypeShare: number; - }[] - UserName: string - Profile: any; - UserPermissions: any; -} - - export class calendarInterface { CalendarId: string CalendarName: "Oficial" | "Pessoal"; @@ -50,44 +15,12 @@ export class calendarInterface { } export class UserSession { - BasicAuthKey: string; UserId: number; Authorization: string; - ChatData: { - status: string, - data: { - userId: string, - authToken: string - } - } Email: string FullName: string - ManagerName: string - OwnerCalendars: { - CalendarId: string - CalendarName: "Oficial" | "Pessoal"; - CalendarRoleId: string; - Id: number; - OwnerUserId: any - }[] RoleDescription: string RoleID: number - SharedCalendars: { - CalendarId: string - CalendarName: "Oficial" | "Pessoal"; - /** - * @description User Role Id - */ - CalendarRoleId: string; - Id: number; - OwnerUserId: string; - TypeShare: number; - /** - * @description deprecated - */ - CalendarToken: string; - }[] - UserName: string Password: string RochetChatUserId: string Profile: 'PR' | 'MDGPR' | 'Consultant' | 'SGGPR' | 'Unknown' ; diff --git a/src/app/module/agenda/data/repository/agenda-data-repository.service.ts b/src/app/module/agenda/data/repository/agenda-data-repository.service.ts index c945141aa..8815aa6bc 100644 --- a/src/app/module/agenda/data/repository/agenda-data-repository.service.ts +++ b/src/app/module/agenda/data/repository/agenda-data-repository.service.ts @@ -189,16 +189,16 @@ export class AgendaDataRepositoryService { let body; if(typeof eventData?.Body == 'object') { - body = eventData?.Body?.Text - } else { - body = eventData?.Body + body = eventData.Body.Text + } else if (eventData?.Body) { + body = eventData.Body } let eventInput = { userId: calendar.wxUserId, ownerType: this.utils.selectedCalendarOwner(calendar.role), subject: eventData.Subject, - body: eventData?.Body?.Text, + body: body, location: eventData.Location, startDate: this.utils.addOneHourToIsoString(eventData.StartDate), endDate: this.utils.addOneHourToIsoString(eventData.EndDate), diff --git a/src/app/module/chat/data/repository/room/room-remote-repository.service.ts b/src/app/module/chat/data/repository/room/room-remote-repository.service.ts index 483ec6763..59ab936f6 100644 --- a/src/app/module/chat/data/repository/room/room-remote-repository.service.ts +++ b/src/app/module/chat/data/repository/room/room-remote-repository.service.ts @@ -6,10 +6,10 @@ import { SessionStore } from 'src/app/store/session.service'; import { SignalRService } from 'src/app/infra/socket/signalR/signal-r.service'; import { v4 as uuidv4 } from 'uuid' import { CreateRoomInputDTO, RoomOutPutDTO } from '../../../../../core/chat/usecase/room/room-create-use-case.service'; -import { IRoomRemoteRepository } from 'src/app/core/chat/repository/room/room-remote-repository'; +import { IRoomRemoteRepository, ISearchRoom } from 'src/app/core/chat/repository/room/room-remote-repository'; import { RoomByIdOutputDTO } from 'src/app/core/chat/usecase/room/room-get-by-id-use-case.service'; import { RoomUpdateInputDTO, RoomUpdateOutputDTO } from 'src/app/core/chat/usecase/room/room-update-by-id-use-case.service'; -import { RoomListOutPutDTO } from '../../../../../core/chat/usecase/room/room-get-list-use-case.service'; +import { RoomListItemOutPutDTO, RoomListItemSchema, RoomListOutPutDTO } from '../../../../../core/chat/usecase/room/room-get-list-use-case.service'; import { z } from 'zod'; import { HttpAdapter } from 'src/app/infra/http/adapter'; import { AddMemberToRoomInputDTO } from 'src/app/core/chat/usecase/member/member-add-use-case.service'; @@ -54,6 +54,13 @@ export class RoomRemoteDataSourceService implements IRoomRemoteRepository { return result.map((e)=> e.data) } + + async search(input: string): Promise> { + const result = await this.Http.get(`${this.baseUrl}/search?value=${input}`); + + return result.map((e)=> ( e.data.data.rooms.map(j => ({ chatRoom: j, joinAt: ''})) )) + } + //@ValidateSchema(RoomUpdateInputDTOSchema) //@APIReturn(RoomByIdOutputDTOSchema,'update/Room/${id}') async updateRoom(data: RoomUpdateInputDTO): Promise> { diff --git a/src/app/module/notification/data/async/changes/notificationListChange.ts b/src/app/module/notification/data/async/changes/notificationListChange.ts index f6570a74a..503740c16 100644 --- a/src/app/module/notification/data/async/changes/notificationListChange.ts +++ b/src/app/module/notification/data/async/changes/notificationListChange.ts @@ -21,7 +21,7 @@ export function NotificationListChanges( const localItem = localMap.get(id); if (!localItem) { changes.insert.push(serverItem); - } else if (localItem.status !== serverItem.status) { + } else if (localItem.viewDate !== serverItem.viewDate) { changes.update.push(serverItem); } } diff --git a/src/app/module/notification/data/datasource/local-notification.service.ts b/src/app/module/notification/data/datasource/local-notification.service.ts index db6b21873..ccf2514ce 100644 --- a/src/app/module/notification/data/datasource/local-notification.service.ts +++ b/src/app/module/notification/data/datasource/local-notification.service.ts @@ -122,7 +122,7 @@ export class LocalNotificationService { return from(liveQuery( () => { return NotificationDataSource.notification.orderBy('createdAt').reverse().toArray() .then(notifications => { - return notifications.filter(notification => notification.status === false) + return notifications.filter(notification => notification.viewDate == null) }) })) } @@ -132,7 +132,7 @@ export class LocalNotificationService { return NotificationDataSource.notification .toArray() .then(notifications => { - return notifications.filter(notification => notification.status === false).length + return notifications.filter(notification => notification.viewDate == null).length }) })) } diff --git a/src/app/module/notification/data/datasource/remote-notification.service.ts b/src/app/module/notification/data/datasource/remote-notification.service.ts index de5cd05fe..71e165be6 100644 --- a/src/app/module/notification/data/datasource/remote-notification.service.ts +++ b/src/app/module/notification/data/datasource/remote-notification.service.ts @@ -22,8 +22,12 @@ export class RemoteNotificationService { } - async notificationStatus(id: string) { + async notificationStatus(id: number) { return await this.httpService.patch(`${this.baseUrl}/Notifications/${id}/status`); } + + async notificationDeleteAll(userId: any) { + return await this.httpService.delete(`${this.baseUrl}/Notifications/${userId}`); + } } diff --git a/src/app/module/notification/data/dto/NotificationOutputDTO.ts b/src/app/module/notification/data/dto/NotificationOutputDTO.ts index 834aa2b54..40b594ddd 100644 --- a/src/app/module/notification/data/dto/NotificationOutputDTO.ts +++ b/src/app/module/notification/data/dto/NotificationOutputDTO.ts @@ -8,7 +8,7 @@ export const NotificationOutputDTOSchema = z.object({ total: z.number(), result: z.array( z.object({ - id: z.string(), + id: z.number(), service: z.string(), title: z.string(), body: z.string(), @@ -17,7 +17,6 @@ export const NotificationOutputDTOSchema = z.object({ folderId: z.string().nullable(), createdAt: z.string(), viewDate: z.string().nullable(), - status: z.boolean(), startDate: z.string().nullable(), endDate: z.string().nullable(), bodyEvent: z.string().nullable(), diff --git a/src/app/module/notification/data/infra/db/notification.db.ts b/src/app/module/notification/data/infra/db/notification.db.ts index 965bea4cc..b7f71624d 100644 --- a/src/app/module/notification/data/infra/db/notification.db.ts +++ b/src/app/module/notification/data/infra/db/notification.db.ts @@ -2,16 +2,16 @@ import { Dexie, EntityTable, liveQuery } from 'Dexie'; import { z } from 'zod'; export const NotificationTableSchema = z.object({ - notificationId: z.string().nullable(), + notificationId: z.number().nullable(), title: z.string().optional().nullable(), service: z.string().nullable(), object: z.string().optional().nullable(), idObject: z.string().nullable(), + viewDate: z.string().nullable(), folderId: z.string().optional().nullable(), dateInit: z.string().optional().nullable(), dateEnd: z.string().optional().nullable(), location: z.string().optional().nullable(), - status: z.boolean().optional(), notificationBody: z.any().optional() }) export type NotificationTable = z.infer diff --git a/src/app/module/notification/data/notification-repository.service.spec.ts b/src/app/module/notification/data/notification-repository.service.spec.ts deleted file mode 100644 index 4b12a2a12..000000000 --- a/src/app/module/notification/data/notification-repository.service.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { TestBed } from '@angular/core/testing'; - -import { NotificationRepositoryService } from './notification-repository.service'; - -describe('NotificationRepositoryService', () => { - let service: NotificationRepositoryService; - - beforeEach(() => { - TestBed.configureTestingModule({}); - service = TestBed.inject(NotificationRepositoryService); - }); - - it('should be created', () => { - expect(service).toBeTruthy(); - }); -}); diff --git a/src/app/module/notification/data/notification-repository.service.ts b/src/app/module/notification/data/notification-repository.service.ts index b75d5a560..b1b87cf49 100644 --- a/src/app/module/notification/data/notification-repository.service.ts +++ b/src/app/module/notification/data/notification-repository.service.ts @@ -83,7 +83,7 @@ export class NotificationRepositoryService { async notificationStatus(item: NotificationTable) { await this.RemoteNotificationService.notificationStatus(item.notificationId) - item.status = true + item.viewDate = new Date().toUTCString() this.LocalNotificationService.updateNotification(item) this this.init() @@ -93,14 +93,14 @@ export class NotificationRepositoryService { async RemoveNotificationStatus(item: NotificationTable) { await this.RemoteNotificationService.notificationStatus(item.notificationId) - item.status = true + item.viewDate = new Date().toUTCString() this.LocalNotificationService.updateNotification(item) this.init() return } async localNotificationStatus(item: NotificationTable) { - item.status = true + item.viewDate = new Date().toUTCString() this.LocalNotificationService.updateNotification(item) this.init() return diff --git a/src/app/module/notification/domain/mapper/notificationListMapper.ts b/src/app/module/notification/domain/mapper/notificationListMapper.ts index e453aecec..4bbf98247 100644 --- a/src/app/module/notification/domain/mapper/notificationListMapper.ts +++ b/src/app/module/notification/domain/mapper/notificationListMapper.ts @@ -14,9 +14,9 @@ export function NotificationListMapper(NotificationOutputDTO: NotificationOutput dateInit: e.startDate, dateEnd: e.endDate, createdAt: e.createdAt, - status: e.status, location: e.location, - notificationBody: e.body + notificationBody: e.body, + viewDate: e.viewDate } )) } diff --git a/src/app/module/notification/domain/notification.service.ts b/src/app/module/notification/domain/notification.service.ts new file mode 100644 index 000000000..6a1b3d86a --- /dev/null +++ b/src/app/module/notification/domain/notification.service.ts @@ -0,0 +1,19 @@ +import { Injectable } from '@angular/core'; +import { INotificationDeleteAllByUserId, NotificationDeleteAllServiceUseCase } from 'src/app/core/notification/use-case/notification-delete-all-use-case.service' + +@Injectable({ + providedIn: 'root' +}) +export class NotificationService { + + constructor( + private NotificationDeleteAllServiceUseCase: NotificationDeleteAllServiceUseCase + ) { } + + + deleteAllNotificationByUserId() { + return this.NotificationDeleteAllServiceUseCase.execute() + } + + +} diff --git a/src/app/module/notification/notification.module.ts b/src/app/module/notification/notification.module.ts new file mode 100644 index 000000000..57ff2f187 --- /dev/null +++ b/src/app/module/notification/notification.module.ts @@ -0,0 +1,15 @@ +import { NgModule } from '@angular/core'; +import { HttpModule } from 'src/app/infra/http/http.module'; + +@NgModule({ + imports: [HttpModule], + providers: [], + declarations: [], + schemas: [], + entryComponents: [] +}) +export class NotificationModule { + + constructor() {} + +} diff --git a/src/app/module/user/data/datasource/user-remote-repository.service.ts b/src/app/module/user/data/datasource/user-remote-repository.service.ts index 882b96336..29898be9e 100644 --- a/src/app/module/user/data/datasource/user-remote-repository.service.ts +++ b/src/app/module/user/data/datasource/user-remote-repository.service.ts @@ -4,16 +4,40 @@ import { environment } from 'src/environments/environment'; import { IProfilePictureInputDTO } from '../dto/profilePictureInputDTO'; import { HttpHeaders } from '@angular/common/http'; import { TracingType } from 'src/app/services/monitoring/opentelemetry/tracer'; - +import { HttpAdapter } from 'src/app/infra/http/adapter'; +import { IUserRepositoryLoginParams, UserRefreshTokenInputDTO } from 'src/app/core/user/repository/user-remote-repository'; +import { UserLoginOutput } from 'src/app/core/user/use-case/user-login-use-case.service'; +import { SessionStore } from 'src/app/store/session.service'; @Injectable({ providedIn: 'root' }) export class UserRemoteRepositoryService { + private baseUrl = 'https://gdapi-dev.dyndns.info/stage/api/v2'; // Your base URL + constructor( - private httpService: HttpService + private httpService: HttpService, + private http: HttpAdapter, ) { } + + // @APIReturn(MessageOutPutDTOSchema, 'get/Messages') + async login(input: IUserRepositoryLoginParams) { + + return await this.http.post(`${this.baseUrl}/Users/login`, input) + } + + // @APIReturn(MessageOutPutDTOSchema, 'get/Messages') + async logout() { + + return await this.http.post(`${this.baseUrl}/Users/${SessionStore.user.UserId}/logout`, {}) + } + + async refreshToken(input: UserRefreshTokenInputDTO) { + + return await this.http.post(`${this.baseUrl}/Users/RefreshToken`, input) + } + getUserProfilePhoto(guid: string, tracing?: TracingType) { const geturl = environment.apiURL + 'UserAuthentication/GetPhoto'; diff --git a/src/app/module/user/domain/service/session.service.ts b/src/app/module/user/domain/service/session.service.ts new file mode 100644 index 000000000..70dc4db52 --- /dev/null +++ b/src/app/module/user/domain/service/session.service.ts @@ -0,0 +1,135 @@ +import { Injectable } from '@angular/core'; +import { UserEntity } from 'src/app/core/user/entity/userEntity'; +import { SHA1 } from 'crypto-js' +import { localstoreService } from 'src/app/store/localstore.service'; +import { Preference } from 'src/app/core/user/entity/preference'; + + +@Injectable({ + providedIn: 'root' +}) +export class SessionService { + + user?:UserEntity + preference = new Preference() + + forceToLoginWithForceToLogInWithPassword = false + private keyName: string; + + constructor() { + + if(this.exist) { + this.keyName = (SHA1("")).toString() + let restore: any = this.getDataFromLocalStorage() + + if(restore?.user) { + this.user = new UserEntity(restore.user) + } + + if(this.preference.LoginPreference == 'Pin') { + this.preference.Inactivity = false + } + } + + } + + + getDataFromLocalStorage() { + return localstoreService.get(this.keyName, {}).user as UserEntity + } + + get exist() { + let restore = localstoreService.get(this.keyName, {}) + let user: UserEntity = restore.user + if(user) { + if(user.Profile) { + console.log('exist') + return true + } + } + + console.log('exist not', restore) + + return false + } + + setLoginPreference(loginPreference: 'None' | 'Password' | 'Pin' | null) { + this.preference.LoginPreference = loginPreference + this.save() + } + + setPin(pin: string) { + this.preference.PIN = SHA1(pin).toString() + this.save() + } + + validatePin(pin: string) { + return this.preference.PIN == SHA1(pin).toString() + } + + needToValidateUser() { + return this.preference.Inactivity + } + + + isUserActive() { + return this.preference.Inactivity + } + + setInativity(value: boolean) { + this.preference.Inactivity = value + this.preference.UrlBeforeInactivity = '' + this.save() + } + + setUrlBeforeInactivity(pathname: string) { + this.preference.UrlBeforeInactivity = pathname + this.save() + } + + get hasPin() { + + if(!this.preference.PIN) { + return false + } + return this.preference.PIN.length >= 2 + + } + + reset(user) { + console.log('reset') + console.log('user', user) + this.user = user + this.setInativity(true) + this.save() + } + + delete() { + console.log('edeletet') + localstoreService.delete(this.keyName) + this.preference = new Preference() + delete this.user + } + + save() { + console.log('save') + localstoreService.set(this.keyName, { + user: this.user, + preference: this.preference + }) + + } + + get getInitials() { + let names = this.user.wxFullName.split(' ') || ' ', + initials = names[0].substring(0, 1).toUpperCase(); + if (names.length > 1) { + initials += names[names.length - 1].substring(0, 1).toUpperCase(); + } + + return initials; + } + +} + +export const SessionStore = new SessionService() diff --git a/src/app/module/user/domain/user.service.ts b/src/app/module/user/domain/user.service.ts new file mode 100644 index 000000000..7393dff5a --- /dev/null +++ b/src/app/module/user/domain/user.service.ts @@ -0,0 +1,38 @@ +import { Injectable } from '@angular/core'; +import { IUserRemoteRepository } from 'src/app/core/user/repository/user-remote-repository'; +import { UserLoginInput, UserLoginUseCaseService } from 'src/app/core/user/use-case/user-login-use-case.service'; +import { UserLogOutUseCaseService } from 'src/app/core/user/use-case/user-log-out-use-case.service'; +import { SessionStore } from './service/session.service' +import { UserEntity } from 'src/app/core/user/entity/userEntity'; +import { UserRefreshTokenService } from 'src/app/core/user/use-case/user-refresh-token.service'; +@Injectable({ + providedIn: 'root' +}) +export class UserService { + + constructor( + private userLoginUseCaseService: UserLoginUseCaseService, + private userLogOutUseCaseService: UserLogOutUseCaseService, + private userRefreshTokenService: UserRefreshTokenService + ) { } + + + async login(input: UserLoginInput) { + const result = await this.userLoginUseCaseService.execute(input) + + if(result.isOk()) { + + // SessionStore.reset(new UserEntity({...result.value, ...result.value.user})) + } + + return result + } + + async logout() { + return await this.userLogOutUseCaseService.execute() + } + + refreshToken() { + return this.userRefreshTokenService.execute() + } +} diff --git a/src/app/module/user/user.module.ts b/src/app/module/user/user.module.ts new file mode 100644 index 000000000..6c6bb9b4b --- /dev/null +++ b/src/app/module/user/user.module.ts @@ -0,0 +1,33 @@ +import { NgModule } from '@angular/core'; +import { HttpModule } from 'src/app/infra/http/http.module'; +import { IUserRemoteRepository } from 'src/app/core/user/repository/user-remote-repository'; +import { UserRemoteRepositoryService } from './data/datasource/user-remote-repository.service'; +import { UserService } from './domain/user.service' + +import { UserLoginUseCaseService } from 'src/app/core/user/use-case/user-login-use-case.service'; +import { UserLogOutUseCaseService } from 'src/app/core/user/use-case/user-log-out-use-case.service'; +import { UserRefreshTokenService } from 'src/app/core/user/use-case/user-refresh-token.service'; + +@NgModule({ + imports: [HttpModule], + providers: [ + { + provide: IUserRemoteRepository, + useClass: UserRemoteRepositoryService, // or MockDataService + }, + // domain service + UserService, + // use case + UserLoginUseCaseService, + UserLogOutUseCaseService, + UserRefreshTokenService + ], + declarations: [], + schemas: [], + entryComponents: [ + + ], +}) +export class UserModule { + constructor() {} +} diff --git a/src/app/pages/events/attendees/attendees.page.ts b/src/app/pages/events/attendees/attendees.page.ts index 18bf296c8..b718f2d83 100644 --- a/src/app/pages/events/attendees/attendees.page.ts +++ b/src/app/pages/events/attendees/attendees.page.ts @@ -2,7 +2,7 @@ import { Component, Input, OnInit } from '@angular/core'; import { EventPerson } from 'src/app/models/eventperson.model'; import { ModalController, NavParams } from '@ionic/angular'; import { ThemeService } from 'src/app/services/theme.service' -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { SessionStore } from 'src/app/store/session.service'; import { Router } from '@angular/router'; import { ContactRepositoryService } from 'src/app/services/Repositorys/contacts/repository/contacts-repository.service'; @@ -25,7 +25,7 @@ export class AttendeesPageModal implements OnInit { taskParticipants:EventPerson[] = []; taskParticipantsCc:EventPerson[] = []; - loggeduser: LoginUserRespose; + loggeduser: UserSession; hideExternalDomain = true; taskType: any; diff --git a/src/app/pages/gabinete-digital/despachos-pr/despacho-pr/despacho-pr.page.html b/src/app/pages/gabinete-digital/despachos-pr/despacho-pr/despacho-pr.page.html index 64503a241..9ddf21362 100644 --- a/src/app/pages/gabinete-digital/despachos-pr/despacho-pr/despacho-pr.page.html +++ b/src/app/pages/gabinete-digital/despachos-pr/despacho-pr/despacho-pr.page.html @@ -33,7 +33,7 @@
- + diff --git a/src/app/pages/gabinete-digital/despachos-pr/despacho-pr/despacho-pr.page.ts b/src/app/pages/gabinete-digital/despachos-pr/despacho-pr/despacho-pr.page.ts index b6cef208a..74f66fa42 100644 --- a/src/app/pages/gabinete-digital/despachos-pr/despacho-pr/despacho-pr.page.ts +++ b/src/app/pages/gabinete-digital/despachos-pr/despacho-pr/despacho-pr.page.ts @@ -278,6 +278,32 @@ export class DespachoPrPage implements OnInit { } + async executadoPR(note: string, documents: any) { + let body = { + "serialNumber": this.serialNumber, + "action": "Executado", + "ActionTypeId": 95, + "dataFields": { + "ReviewUserComment": note, + }, + "AttachmentList": documents, + } + + const loader = this.toastService.loading() + + try { + await this.processes.CompleteTask(body).toPromise() + this.httpErroHandle.httpsSucessMessagge('Executado') + this.TaskService.loadDiplomas() + } catch (error) { + this.httpErroHandle.httpStatusHandle(error) + } + finally { + loader.remove() + } + + } + async arquivar(note: string, documents: any) { let body = { "serialNumber": this.serialNumber, @@ -447,6 +473,8 @@ export class DespachoPrPage implements OnInit { } else if (actionName == 'Reexecutar') { await this.reexecutar(res.data.note, docs); + } else if (actionName == 'Executado1') { + await this.executadoPR(res.data.note, docs) } this.TaskService.loadDiplomas() diff --git a/src/app/pages/gabinete-digital/despachos/despacho/despacho.page.ts b/src/app/pages/gabinete-digital/despachos/despacho/despacho.page.ts index 9146540ee..ad756f797 100644 --- a/src/app/pages/gabinete-digital/despachos/despacho/despacho.page.ts +++ b/src/app/pages/gabinete-digital/despachos/despacho/despacho.page.ts @@ -3,7 +3,7 @@ import { ProcessesService } from 'src/app/services/processes.service'; import { ActivatedRoute } from '@angular/router'; import { Event } from '../../../../models/event.model'; import { MenuController, ModalController, PopoverController } from '@ionic/angular'; -import { momentG } from 'src/plugin/momentG' +import { momentG } from 'src/plugin/momentG'; import { DiscartExpedientModalPage } from '../../discart-expedient-modal/discart-expedient-modal.page'; import { BookMeetingModalPage } from '../../expediente/book-meeting-modal/book-meeting-modal.page'; import { CreateProcessPage } from 'src/app/modals/create-process/create-process.page'; diff --git a/src/app/pages/gabinete-digital/diplomas-assinar/diploma-assinar/diploma-assinar.page.html b/src/app/pages/gabinete-digital/diplomas-assinar/diploma-assinar/diploma-assinar.page.html index b04da82e8..d6c3089a5 100644 --- a/src/app/pages/gabinete-digital/diplomas-assinar/diploma-assinar/diploma-assinar.page.html +++ b/src/app/pages/gabinete-digital/diplomas-assinar/diploma-assinar/diploma-assinar.page.html @@ -6,6 +6,7 @@ [task]=task [intervenientes]=intervenientes [cc]=cc + [fulltask]="fulltask" [customDate]=customDate [mergedArray]="mergedArray" (openOptions)= openOptions() diff --git a/src/app/pages/gabinete-digital/diplomas-assinar/diploma-assinar/diploma-assinar.page.ts b/src/app/pages/gabinete-digital/diplomas-assinar/diploma-assinar/diploma-assinar.page.ts index 224838b50..f8554f3b4 100644 --- a/src/app/pages/gabinete-digital/diplomas-assinar/diploma-assinar/diploma-assinar.page.ts +++ b/src/app/pages/gabinete-digital/diplomas-assinar/diploma-assinar/diploma-assinar.page.ts @@ -88,6 +88,7 @@ export class DiplomaAssinarPage implements OnInit { } async openOptions(taskAction?: any) { + console.log('openOptions') if (window.innerWidth > 500) { this.showOptions = true @@ -139,11 +140,12 @@ export class DiplomaAssinarPage implements OnInit { "TaskStartDate": res.taskStartDate, "InstanceID": res.workflowInstanceDataFields.InstanceID, "FolderID": res.workflowInstanceDataFields.FolderID, - "DraftIds": res.workflowInstanceDataFields?.DraftIds + "DraftIds": res.workflowInstanceDataFields?.DraftIds, } console.log('draftidsss',res.workflowInstanceDataFields.DraftIds); this.fulltask = res; + console.log('this.fulltask', this.fulltask ) let stringDraft = res.workflowInstanceDataFields.DraftIds; this.DraftIds = res.workflowInstanceDataFields.DraftIds console.log('draftidsss 111',this.DraftIds); diff --git a/src/app/pages/gabinete-digital/event-list/approve-event/approve-event.page.html b/src/app/pages/gabinete-digital/event-list/approve-event/approve-event.page.html index ae92e5fe8..953a68515 100644 --- a/src/app/pages/gabinete-digital/event-list/approve-event/approve-event.page.html +++ b/src/app/pages/gabinete-digital/event-list/approve-event/approve-event.page.html @@ -107,7 +107,7 @@
- +
diff --git a/src/app/pages/gabinete-digital/expediente/book-meeting-modal/book-meeting-modal.page.ts b/src/app/pages/gabinete-digital/expediente/book-meeting-modal/book-meeting-modal.page.ts index 28029cb98..8319aa03f 100644 --- a/src/app/pages/gabinete-digital/expediente/book-meeting-modal/book-meeting-modal.page.ts +++ b/src/app/pages/gabinete-digital/expediente/book-meeting-modal/book-meeting-modal.page.ts @@ -7,7 +7,7 @@ import { DiscartExpedientModalPage } from '../../discart-expedient-modal/discart import { AttachmentsService } from 'src/app/services/attachments.service'; import { SearchPage } from 'src/app/pages/search/search.page'; import { SearchList } from 'src/app/models/search-document'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { AttendeesPageModal } from 'src/app/pages/events/attendees/attendees.page'; import { ToastService } from 'src/app/services/toast.service'; import { FormControl, FormGroup, Validators } from '@angular/forms'; @@ -111,7 +111,7 @@ export class BookMeetingModalPage implements OnInit { sessionStore = SessionStore; SessionStore=SessionStore environment = environment - loggeduser: LoginUserRespose; + loggeduser: UserSession; eventPersons: EventPerson[]; contacts: EventPerson[]; diff --git a/src/app/pages/gabinete-digital/expediente/expedient-task-modal/expedient-task-modal.page.ts b/src/app/pages/gabinete-digital/expediente/expedient-task-modal/expedient-task-modal.page.ts index 35b0928b2..ec2afc21b 100644 --- a/src/app/pages/gabinete-digital/expediente/expedient-task-modal/expedient-task-modal.page.ts +++ b/src/app/pages/gabinete-digital/expediente/expedient-task-modal/expedient-task-modal.page.ts @@ -12,7 +12,7 @@ import { ExpedienteDetailPage } from '../expediente-detail/expediente-detail.pag import { AlertService } from 'src/app/services/alert.service'; import { SearchPage } from 'src/app/pages/search/search.page'; import { SearchList } from 'src/app/models/search-document'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { ToastService } from 'src/app/services/toast.service'; import { AttendeesPageModal } from 'src/app/pages/events/attendees/attendees.page'; import { FormControl, FormGroup, Validators } from '@angular/forms'; @@ -98,7 +98,7 @@ export class ExpedientTaskModalPage implements OnInit { taskResult: any = {} - loggeduser: LoginUserRespose; + loggeduser: UserSession; toppings = new FormControl(); Form: FormGroup; @@ -371,6 +371,7 @@ export class ExpedientTaskModalPage implements OnInit { UsersSelected: attendees, DispatchFolder: this.dispatchFolder, AttachmentList: docs, + dataFields: {} } let action_despacho = { @@ -405,7 +406,8 @@ export class ExpedientTaskModalPage implements OnInit { UserEmail: this.loggeduser.Email, UsersSelected: attendees, DispatchFolder: this.dispatchFolder, - AttachmentList: docs + AttachmentList: docs, + dataFields: {} } let action_parecer = { @@ -437,7 +439,8 @@ export class ExpedientTaskModalPage implements OnInit { UserEmail: this.loggeduser.Email, UsersSelected: attendees, DispatchFolder: this.dispatchFolder, - AttachmentList: docs + AttachmentList: docs, + dataFields: {} } // let action_deferimento = { @@ -475,6 +478,7 @@ export class ExpedientTaskModalPage implements OnInit { UsersSelected: attendees, DispatchFolder: this.dispatchFolder, AttachmentList: docs, + dataFields: {} } @@ -519,7 +523,8 @@ export class ExpedientTaskModalPage implements OnInit { UserEmail: this.loggeduser.Email, UsersSelected: attendees, DispatchFolder: this.dispatchFolder, - AttachmentList: docs + AttachmentList: docs, + dataFields: {} } let action_parecer_pr = { diff --git a/src/app/pages/gabinete-digital/expediente/expediente-detail/expediente-detail.page.ts b/src/app/pages/gabinete-digital/expediente/expediente-detail/expediente-detail.page.ts index 86897d3e2..188f75119 100644 --- a/src/app/pages/gabinete-digital/expediente/expediente-detail/expediente-detail.page.ts +++ b/src/app/pages/gabinete-digital/expediente/expediente-detail/expediente-detail.page.ts @@ -26,7 +26,7 @@ import { NewGroupPage } from 'src/app/ui/chat/modal/new-group/new-group.page'; import { DataService } from 'src/app/services/data.service'; import { RouteService } from 'src/app/services/route.service'; import { Storage } from '@ionic/storage'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { SessionStore } from 'src/app/store/session.service'; import { HttpErrorHandle } from 'src/app/services/http-error-handle.service'; import { TaskService } from 'src/app/services/task.service'; @@ -61,7 +61,7 @@ export class ExpedienteDetailPage implements OnInit { onlinecheck: boolean; - loggeduser: LoginUserRespose; + loggeduser: UserSession; showOptions = false constructor( diff --git a/src/app/pages/gabinete-digital/expedientes-pr/expediente-pr/expediente-pr.page.ts b/src/app/pages/gabinete-digital/expedientes-pr/expediente-pr/expediente-pr.page.ts index 72e440b32..078de86a5 100644 --- a/src/app/pages/gabinete-digital/expedientes-pr/expediente-pr/expediente-pr.page.ts +++ b/src/app/pages/gabinete-digital/expedientes-pr/expediente-pr/expediente-pr.page.ts @@ -7,7 +7,7 @@ import { ViewEventPage } from 'src/app/ui/agenda/modal/view-event/view-event.pag import { DiscartExpedientModalPage } from '../../discart-expedient-modal/discart-expedient-modal.page'; import { ExpedientTaskModalPage } from '../../expediente/expedient-task-modal/expedient-task-modal.page'; import { BookMeetingModalPage } from '../../expediente/book-meeting-modal/book-meeting-modal.page'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { AddNotePage } from 'src/app/modals/add-note/add-note.page'; import { OptsExpedientePrPage } from 'src/app/shared/popover/opts-expediente-pr/opts-expediente-pr.page'; import { ToastService } from 'src/app/services/toast.service'; @@ -41,7 +41,7 @@ export class ExpedientePrPage implements OnInit { intervenientes: any = []; cc: any = []; - loggeduser: LoginUserRespose; + loggeduser: UserSession; documents: SearchList[] = []; attachments:any; isDelegated: boolean; diff --git a/src/app/pages/gabinete-digital/expedientes-pr/expedientes-pr.page.ts b/src/app/pages/gabinete-digital/expedientes-pr/expedientes-pr.page.ts index 190a58916..6f1e24aa8 100644 --- a/src/app/pages/gabinete-digital/expedientes-pr/expedientes-pr.page.ts +++ b/src/app/pages/gabinete-digital/expedientes-pr/expedientes-pr.page.ts @@ -4,7 +4,7 @@ import { CalendarComponent } from 'ionic2-calendar'; import { ProcessesService } from 'src/app/services/processes.service'; import { ModalController } from '@ionic/angular'; import { ExpedienteDetailPage } from 'src/app/pages/gabinete-digital/expediente/expediente-detail/expediente-detail.page'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { ExpedienteGdStore } from 'src/app/store/expedientegd-store.service'; import { ExpedienteTaskPipe } from 'src/app/pipes/expediente-task.pipe'; import { ThemeService } from 'src/app/services/theme.service' @@ -26,7 +26,7 @@ export class ExpedientesPrPage implements OnInit { serialNumber:string; showLoader:boolean; - loggeduser: LoginUserRespose; + loggeduser: UserSession; @Output() openExpedientDetail:EventEmitter = new EventEmitter(); skeletonLoader = true diff --git a/src/app/pages/gabinete-digital/gabinete-digital.page.html b/src/app/pages/gabinete-digital/gabinete-digital.page.html index 68cb8861a..baf23f8db 100644 --- a/src/app/pages/gabinete-digital/gabinete-digital.page.html +++ b/src/app/pages/gabinete-digital/gabinete-digital.page.html @@ -150,11 +150,11 @@
+
-
diff --git a/src/app/pages/gabinete-digital/gabinete-digital.page.ts b/src/app/pages/gabinete-digital/gabinete-digital.page.ts index ebbd7687c..a8f53d4a6 100644 --- a/src/app/pages/gabinete-digital/gabinete-digital.page.ts +++ b/src/app/pages/gabinete-digital/gabinete-digital.page.ts @@ -1,7 +1,7 @@ import { Component, ElementRef, OnInit, ViewChild } from '@angular/core'; import {NavigationEnd, NavigationExtras, Router } from '@angular/router'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { ExpedientsPage } from 'src/app/shared/gabinete-digital/expedients/expedients.page'; import { PendentesPage } from 'src/app/shared/gabinete-digital/pendentes/pendentes.page'; import { EventsToApprovePage } from 'src/app/shared/gabinete-digital/events-to-approve/events-to-approve.page'; @@ -57,7 +57,7 @@ export class GabineteDigitalPage implements OnInit { serialNumber: string; - loggeduser: LoginUserRespose; + loggeduser: UserSession; mdgpr = "MDGPR"; pr = "PR"; @@ -461,8 +461,11 @@ export class GabineteDigitalPage implements OnInit { async loadAllProcesses() { this.skeletonLoader = true - await this.TaskService.LoadTask(); - this.dynamicSearch(); + try { + + await this.TaskService.LoadTask(); + this.dynamicSearch(); + } catch (e) {} this.skeletonLoader = false } diff --git a/src/app/pages/gabinete-digital/pedidos/pedido/pedido.page.ts b/src/app/pages/gabinete-digital/pedidos/pedido/pedido.page.ts index d90913c4c..549096c3f 100644 --- a/src/app/pages/gabinete-digital/pedidos/pedido/pedido.page.ts +++ b/src/app/pages/gabinete-digital/pedidos/pedido/pedido.page.ts @@ -10,7 +10,7 @@ import { CreateProcessPage } from 'src/app/modals/create-process/create-process. import { DelegarPage } from 'src/app/modals/delegar/delegar.page'; import { DarParecerPage } from 'src/app/modals/dar-parecer/dar-parecer.page'; import { AddNotePage } from 'src/app/modals/add-note/add-note.page'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { ToastService } from 'src/app/services/toast.service'; import { ForwardPage } from 'src/app/modals/forward/forward.page'; @@ -47,7 +47,7 @@ export class PedidoPage implements OnInit { caller: string; intervenientes: any = [] cc: any = []; - loggeduser: LoginUserRespose; + loggeduser: UserSession; taskArrayActions = []; showOptions = false diff --git a/src/app/pages/gabinete-digital/pendentes/pendentes.page.ts b/src/app/pages/gabinete-digital/pendentes/pendentes.page.ts index 1a1c729e5..6627692ae 100644 --- a/src/app/pages/gabinete-digital/pendentes/pendentes.page.ts +++ b/src/app/pages/gabinete-digital/pendentes/pendentes.page.ts @@ -6,7 +6,7 @@ import { customTask } from '../../../models/dailyworktask.model'; import { ProcessesService } from 'src/app/services/processes.service'; import { AlertService } from 'src/app/services/alert.service'; import { PendentesStore } from 'src/app/store/pendestes-store.service'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { AuthService } from 'src/app/services/auth.service'; import { CustomTaskPipe } from 'src/app/pipes/custom-task.pipe'; @@ -31,7 +31,7 @@ export class PendentesPage implements OnInit { serialNumber: string; totalDocs: any; showLoader: boolean; - loggeduser: LoginUserRespose; + loggeduser: UserSession; @Input() profile: string; segment: string; diff --git a/src/app/pages/inactivity/inactivity.page.ts b/src/app/pages/inactivity/inactivity.page.ts index b7afc603a..24f9fa2a0 100644 --- a/src/app/pages/inactivity/inactivity.page.ts +++ b/src/app/pages/inactivity/inactivity.page.ts @@ -86,7 +86,7 @@ export class InactivityPage implements OnInit { // if current attemp is equal to the current user if (attempt.UserId == SessionStore.user.UserId) { - await this.authService.SetSession(attempt, this.userattempt); + // await this.authService.SetSession(attempt, this.userattempt); if (this.p.userPermission(this.p.permissionList.Chat.access)) { // this.authService.loginChat(); @@ -101,7 +101,7 @@ export class InactivityPage implements OnInit { window.localStorage.clear(); SessionStore.setInativity(true) - await this.authService.SetSession(attempt, this.userattempt); + // await this.authService.SetSession(attempt, this.userattempt); } this.enterWithPassword = false @@ -174,7 +174,8 @@ export class InactivityPage implements OnInit { if (this.p.userPermission(this.p.permissionList.Agenda.access) || this.p.userPermission(this.p.permissionList.Gabinete.access)) { //When user has got access to Agenda but does not have their own calendar, goes to Agenda - if (this.p.userPermission(this.p.permissionList.Agenda.access) && SessionStore?.user?.OwnerCalendars?.length == 0) { + //if (this.p.userPermission(this.p.permissionList.Agenda.access) && SessionStore?.user?.OwnerCalendars?.length == 0) { + if (this.p.userPermission(this.p.permissionList.Agenda.access)) { this.router.navigate(['/home/agenda']); } else { diff --git a/src/app/pages/login/login.module.ts b/src/app/pages/login/login.module.ts index 6828de197..cdff46d34 100644 --- a/src/app/pages/login/login.module.ts +++ b/src/app/pages/login/login.module.ts @@ -7,13 +7,15 @@ import { IonicModule } from '@ionic/angular'; import { LoginPageRoutingModule } from './login-routing.module'; import { LoginPage } from './login.page'; +import { UserModule } from 'src/app/module/user/user.module'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, - LoginPageRoutingModule + LoginPageRoutingModule, + UserModule ], declarations: [ LoginPage diff --git a/src/app/pages/login/login.page.ts b/src/app/pages/login/login.page.ts index c44b1a4cb..1b2e452b7 100644 --- a/src/app/pages/login/login.page.ts +++ b/src/app/pages/login/login.page.ts @@ -1,6 +1,5 @@ import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; -import { AuthService } from 'src/app/services/auth.service'; import { UserForm } from 'src/app/models/user.model'; import { ToastService } from 'src/app/services/toast.service'; import { environment } from 'src/environments/environment'; @@ -21,7 +20,9 @@ import { NotificationRepositoryService } from 'src/app/module/notification/data/ import { ChatServiceService } from 'src/app/module/chat/domain/chat-service.service'; import { RoomLocalRepository } from 'src/app/module/chat/data/repository/room/room-local-repository.service' import { MessageLocalDataSourceService } from 'src/app/module/chat/data/repository/message/message-local-data-source.service' - +import { UserService } from 'src/app/module/user/domain/user.service' +import { HttpErrorHandle } from 'src/app/services/http-error-handle.service'; +import { LoginError } from 'src/app/core/user/use-case/user-login-use-case.service'; @Component({ selector: 'app-login', @@ -47,14 +48,12 @@ export class LoginPage implements OnInit { constructor( private notificatinsservice: NotificationsService, private router: Router, - private authService: AuthService, private toastService: ToastService, public alertController: AlertController, private clearStoreService: ClearStoreService, private changeProfileService: ChangeProfileService, public ThemeService: ThemeService, public p: PermissionService, - // public ChatSystemService: ChatSystemService, private platform: Platform, private storage: Storage, private storageService: StorageService, @@ -63,7 +62,9 @@ export class LoginPage implements OnInit { private NotificationRepositoryService: NotificationRepositoryService, private ChatServiceService: ChatServiceService, private RoomLocalRepository: RoomLocalRepository, - private MessageLocalDataSourceService: MessageLocalDataSourceService + private MessageLocalDataSourceService: MessageLocalDataSourceService, + private UserService:UserService, + private httpErroHandle: HttpErrorHandle, ) { } ngOnInit() { } @@ -132,36 +133,31 @@ export class LoginPage implements OnInit { const loader = this.toastService.loading() - let attempt = await this.authService.login(this.userattempt, { saveSession: false }) - /* const data = await this.authService.loginContenteProduction(this.userattempt, { saveSession: true }) */ + let attempt = await this.UserService.login({ + username: newUserName.trim(), + password: this.password.trim(), + }) loader.remove() - if (attempt) { + if (attempt.isOk()) { - if (attempt.UserId == SessionStore.user.UserId) { + if (attempt.value.UserId == SessionStore.user.UserId) { - await this.authService.SetSession(attempt, this.userattempt); + // await this.authService.SetSession(attempt.value, this.userattempt); this.changeProfileService.run(); - if (attempt.ChatData) { + try { + await this.AgendaDataRepositoryService.getSharedCalendar() - try { + this.NotificationHolderService.clear() - await this.AgendaDataRepositoryService.getSharedCalendar() - - this.NotificationHolderService.clear() - await this.authService.loginToChatWs(); - - - this.NotificationRepositoryService.init() - - } catch(error) { - console.log("faild to clear chat") - } + this.NotificationRepositoryService.init() + } catch(error) { + console.log("faild to clear chat") } this.changeProfileService.runLogin(); @@ -189,7 +185,7 @@ export class LoginPage implements OnInit { window.localStorage.clear(); this.storage.clear(); - await this.authService.SetSession(attempt, this.userattempt); + // await this.authService.SetSession(attempt.value, this.userattempt); this.NotificationRepositoryService.init() /* CPSession.save(data) */ @@ -213,10 +209,11 @@ export class LoginPage implements OnInit { SessionStore.hasPassLogin = true; } - }/* - else{ - this.toastService._badRequest('Ocorreu um problema por favor valide o username e password'); - } */ + } else { + if( typeof attempt.error == 'number') { + this.httpErroHandle.httpStatusHandle({ status: attempt.error as LoginError}) + } + } } else { this.toastService._badRequest('Por favor, insira a sua palavra-passe'); @@ -236,8 +233,9 @@ export class LoginPage implements OnInit { } else { if (this.p.userPermission(this.p.permissionList.Agenda.access) || this.p.userPermission(this.p.permissionList.Gabinete.access)) { //When user has got access to Agenda but does not have their own calendar, goes to Agenda - if (this.p.userPermission(this.p.permissionList.Agenda.access) && SessionStore?.user?.OwnerCalendars.length == 0) { - this.router.navigate(['/home/agenda']); + //if (this.p.userPermission(this.p.permissionList.Agenda.access) && SessionStore?.user?.OwnerCalendars.length == 0) { + if (this.p.userPermission(this.p.permissionList.Agenda.access)) { + this.router.navigate(['/home/events']); } else { this.router.navigate(['/home/events']); diff --git a/src/app/services/attachments.service.ts b/src/app/services/attachments.service.ts index 9d973afd8..767d09ba1 100644 --- a/src/app/services/attachments.service.ts +++ b/src/app/services/attachments.service.ts @@ -3,7 +3,7 @@ import { Attachment } from '../models/attachment.model'; import { Observable } from 'rxjs'; import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { environment } from 'src/environments/environment'; -import { LoginUserRespose } from '../models/user.model'; +import { UserSession } from '../models/user.model'; import { SessionStore } from '../store/session.service'; import { File } from '@ionic-native/file/ngx'; import { Platform } from '@ionic/angular'; @@ -14,7 +14,7 @@ import { ChangeProfileService } from './change-profile.service'; }) export class AttachmentsService { - loggeduser: LoginUserRespose; + loggeduser: UserSession; headers: HttpHeaders; constructor( diff --git a/src/app/services/auth.service.ts b/src/app/services/auth.service.ts index 7499de140..39127569d 100644 --- a/src/app/services/auth.service.ts +++ b/src/app/services/auth.service.ts @@ -1,7 +1,7 @@ import { Injectable, ErrorHandler } from '@angular/core'; import { StorageService } from './storage.service'; import { HttpClient, HttpHeaders, HttpEventType } from '@angular/common/http'; -import { LoginUserRespose, UserForm, UserSession } from '../models/user.model'; +import { UserForm, UserSession } from '../models/user.model'; import { environment } from 'src/environments/environment'; import { BehaviorSubject, of } from 'rxjs'; import { AlertController, Platform } from '@ionic/angular'; @@ -15,6 +15,7 @@ import { PermissionService } from './permission.service'; import { HttpErrorHandle } from 'src/app/services/http-error-handle.service'; import { captureException } from '@sentry/angular'; import { catchError, tap } from 'rxjs/operators'; +import { UserLoginOutput } from '../core/user/use-case/user-login-use-case.service'; @Injectable({ providedIn: 'root' }) @@ -42,35 +43,9 @@ export class AuthService { private errorHandler: ErrorHandler, private platform: Platform,) { - if (SessionStore.exist) { - if (this.p.userPermission(this.p.permissionList.Chat.access) == true) { - this.loginToChatWs() - } - - } - - window.addEventListener('focus', (event) => { - if (!this.tabIsActive) { - this.tabIsActive = true - const data = SessionStore.getDataFromLocalStorage(); - - if (!data?.user?.Authorization && SessionStore?.user?.Authorization) { - window.location.reload(); - } - - if (window['all-process-gabinete']) { - window['all-process-gabinete']() - } - } - }); - - window.addEventListener('blur', (event) => { - this.tabIsActive = false - }); - } - async login(user: UserForm, { saveSession = true }): Promise { + async login(user: UserForm, { saveSession = true }): Promise { user.BasicAuthKey = btoa(user.username + ':' + this.aesencrypt.encrypt(user.password, user.username)); this.headers = this.headers.set('Authorization', user.BasicAuthKey); @@ -95,11 +70,11 @@ export class AuthService { let response: any; try { - response = await this.http.post(environment.apiURL + "UserAuthentication/Login", body, this.opts).toPromise(); + response = await this.http.post(environment.apiURL + "UserAuthentication/Login", body, this.opts).toPromise(); if (saveSession) { - this.SetSession(response, user) + // this.SetSession(response, user) } } catch (error) { this.errorHandler.handleError(error); @@ -116,128 +91,37 @@ export class AuthService { } - async loginContenteProduction(user: UserForm, { saveSession = true }): Promise { - user.BasicAuthKey = 'Basic ' + btoa(user.username + ':' + this.aesencrypt.encrypt(user.password, user.username)); + // async loginContenteProduction(user: UserForm, { saveSession = true }): Promise { + // user.BasicAuthKey = 'Basic ' + btoa(user.username + ':' + this.aesencrypt.encrypt(user.password, user.username)); - this.headers = this.headers.set('Authorization', user.BasicAuthKey); - this.opts = { - headers: this.headers, - } + // this.headers = this.headers.set('Authorization', user.BasicAuthKey); + // this.opts = { + // headers: this.headers, + // } - let response: any; + // let response: any; - try { - response = await this.http.post(environment.apiURL + "UserAuthentication/Login", '', this.opts).toPromise(); - console.log('JWT', response) + // try { + // response = await this.http.post(environment.apiURL + "UserAuthentication/Login", '', this.opts).toPromise(); + // console.log('JWT', response) - if (saveSession) { - /* this.SetSession(response, user) */ - console.log('teste', response); + // if (saveSession) { + // /* this.SetSession(response, user) */ + // console.log('teste', response); - return response + // return response - } - } catch (error) { - this.httpErroHandle.httpStatusHandle(error) - } finally { - return response - } + // } + // } catch (error) { + // this.httpErroHandle.httpStatusHandle(error) + // } finally { + // return response + // } - } + // } // async UpdateLogin() {} - SetSession(response: LoginUserRespose, user: UserForm) { - const session: UserSession = Object.assign(SessionStore.user, response) - - if (response) { - if (session.RoleID == 100000014) { - session.Profile = 'PR' - } else if (session.RoleID == 100000011) { - session.Profile = 'MDGPR' - } else if (session.RoleID == 99999872) { - session.Profile = 'Consultant' - } else if (session.RoleID == 99999886) { - session.Profile = 'SGGPR' - } else { - session.Profile = 'Unknown' - } - - session.Password = user.password - session.BasicAuthKey = user.BasicAuthKey - SessionStore.reset(session) - - return true; - } - - this.initialsService.getInitials(session.FullName); - } - - loginToChatWs() { - setTimeout(() => { - - if (SessionStore.user.ChatData?.data) { - // this.RochetChatConnectorService.logout(); - // this.RochetChatConnectorService.connect(); - // this.RochetChatConnectorService.login().then((message: any) => { - // console.log('Chat login', message) - - // SessionStore.user.RochetChatUserId = message.result.id - // SessionStore.save() - - // this.ChatSystemService.loadChat() - // this.RochetChatConnectorService.setStatus('online') - // window['RochetChatConnectorService'] = this.RochetChatConnectorService - // setTimeout(() => { - // this.ChatSystemService.getAllRooms(); - // this.RochetChatConnectorService.setStatus('online') - // }, 200); - - - // }).catch((error) => { - // console.error(SessionStore.user.ChatData, 'web socket login', error) - - // if(window.location.pathname.includes('/home/')) { - // setTimeout(() => { - // this.loginToChatWs(); - // }, 4000) - // } - - // }) - } - - - - // before sending a message with a attachment -8 - // this.NfService.downloadFileMsg = async (message: MessageService, room?: RoomService) => { - - // // - // let downloadFile = ""; - // if (message.file.type == "application/img") { - // const event: any = await this.AttachmentsService.downloadFile(message.file.guid).toPromise(); - - // if (event.type === HttpEventType.DownloadProgress) { - // //this.downloadProgess = Math.round((100 * event.loaded) / event.total); - // return true - // } else if (event.type === HttpEventType.Response) { - // downloadFile = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), '')); - - // message.file = { - // guid: message.file.guid, - // image_url: downloadFile, - // type: message.file.type - // } - - // return true - // } - // return false - // } - // }; - - }, 1) - } - autologout(expirationDate: number) { setTimeout(() => { this.logout(); @@ -268,50 +152,50 @@ export class AuthService { await alert.present(); } - async logoutUser() { + // async logoutUser() { - this.headers = this.headers.set('Authorization', 'Bearer ' + SessionStore.user.Authorization); + // this.headers = this.headers.set('Authorization', 'Bearer ' + SessionStore.user.Authorization); - this.opts = { - headers: this.headers, - } + // this.opts = { + // headers: this.headers, + // } - let response: any; - try { - response = await this.http.delete(environment.apiURL + "userauthentication/Logout", this.opts).toPromise(); - SessionStore.user.Authorization = ""; - SessionStore.user.RefreshToken = ""; - } catch (error) { - this.errorHandler.handleError(error); - this.httpErroHandle.loginHttpStatusHandle(error) - captureException(error); + // let response: any; + // try { + // response = await this.http.delete(environment.apiURL + "userauthentication/Logout", this.opts).toPromise(); + // SessionStore.user.Authorization = ""; + // SessionStore.user.RefreshToken = ""; + // } catch (error) { + // this.errorHandler.handleError(error); + // this.httpErroHandle.loginHttpStatusHandle(error) + // captureException(error); - if(error?.status == 403) { - console.log('error?.status == 403') - } + // if(error?.status == 403) { + // console.log('error?.status == 403') + // } - } finally { - return response - } - } + // } finally { + // return response + // } + // } - refreshToken() { + // refreshToken() { - return this.http - .put(environment.apiURL + "UserAuthentication/RefreshToken", { - refreshToken: SessionStore.user.RefreshToken, - },) - .pipe( - tap((tokens) => { - console.log(tokens) - SessionStore.user.Authorization = tokens.Authorization; - SessionStore.user.RefreshToken = tokens.refreshToken; + // return this.http + // .put(environment.apiURL + "UserAuthentication/RefreshToken", { + // refreshToken: SessionStore.user.RefreshToken, + // },) + // .pipe( + // tap((tokens) => { + // console.log(tokens) + // SessionStore.user.Authorization = tokens.Authorization; + // SessionStore.user.RefreshToken = tokens.refreshToken; - }), - catchError((error) => { - this.logoutUser(); - return of(false); - }) - ); - } + // }), + // catchError((error) => { + // this.logoutUser(); + // return of(false); + // }) + // ); + // } } diff --git a/src/app/services/decorator/api-validate-schema.decorator.ts b/src/app/services/decorator/api-validate-schema.decorator.ts index 75cc726b8..be7e8cc67 100644 --- a/src/app/services/decorator/api-validate-schema.decorator.ts +++ b/src/app/services/decorator/api-validate-schema.decorator.ts @@ -33,7 +33,7 @@ export function APIReturn(schema: z.ZodTypeAny, path: string) { tracing?.setAttribute?.('map.error.schema-'+i, JSON.stringify(schema)) } - tracing.log('API return '+ path, { + tracing?.log?.('API return '+ path, { data: result?.value, issues: error?.errors }) @@ -79,7 +79,7 @@ export function APINODReturn(schema: z.ZodTypeAny, data , path: string, tracing? tracing?.setAttribute('map.error.schema-'+i, JSON.stringify(schema)) } - tracing.log('API return '+ path, { + tracing?.log?.('API return '+ path, { data, issues: error?.errors }) diff --git a/src/app/services/first-enter.service.ts b/src/app/services/first-enter.service.ts index 718420092..ba1c5c483 100644 --- a/src/app/services/first-enter.service.ts +++ b/src/app/services/first-enter.service.ts @@ -18,7 +18,8 @@ export class FirstEnterService { enter( ) { if(this.p.userPermission(this.p.permissionList.Agenda.access) || this.p.userPermission(this.p.permissionList.Gabinete.access)){ //When user has got access to Agenda but does not have their own calendar, goes to Agenda - if(this.p.userPermission(this.p.permissionList.Agenda.access) && SessionStore.user?.OwnerCalendars?.length == 0){ + //if(this.p.userPermission(this.p.permissionList.Agenda.access) && SessionStore.user?.OwnerCalendars?.length == 0){ + if(this.p.userPermission(this.p.permissionList.Agenda.access)) { this.router.navigate(['/home/agenda']); } else{ diff --git a/src/app/services/monitoring/opentelemetry/opentelemetry.ts b/src/app/services/monitoring/opentelemetry/opentelemetry.ts index aa94ed3d5..a0460ab28 100644 --- a/src/app/services/monitoring/opentelemetry/opentelemetry.ts +++ b/src/app/services/monitoring/opentelemetry/opentelemetry.ts @@ -37,6 +37,7 @@ function createProvider(serviceName) { // Example usage: export const OpentelemetryChatProvider = createProvider('FO-chat-service'); +export const OpentelemetryUserProvider = createProvider('FO-User-service'); export const OpentelemetryAgendaProvider = createProvider('FO-agenda-service'); export const OpentelemetryNotificationProvider = createProvider('FO-notification'); export const OpentelemetryInterceptorProvider = createProvider('FO-interceptor'); diff --git a/src/app/services/monitoring/opentelemetry/tracer.ts b/src/app/services/monitoring/opentelemetry/tracer.ts index d1f0c2069..8e608915f 100644 --- a/src/app/services/monitoring/opentelemetry/tracer.ts +++ b/src/app/services/monitoring/opentelemetry/tracer.ts @@ -1,7 +1,7 @@ import { v4 as uuidv4 } from 'uuid'; import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; import { Tracer, Span } from '@opentelemetry/sdk-trace-base'; -import { OpentelemetryAgendaProvider, OpentelemetryChatProvider, OpentelemetryInterceptorProvider, OpentelemetryLogging, OpentelemetryNotificationProvider } from './opentelemetry'; +import { OpentelemetryAgendaProvider, OpentelemetryChatProvider, OpentelemetryInterceptorProvider, OpentelemetryLogging, OpentelemetryNotificationProvider, OpentelemetryUserProvider } from './opentelemetry'; import { Device, DeviceInfo } from '@capacitor/device'; import { SessionStore } from 'src/app/store/session.service'; import { environment } from 'src/environments/environment'; @@ -14,6 +14,9 @@ import { Logger } from '../../logger/main/service'; const tracerInstance = OpentelemetryAgendaProvider.getTracer('example-tracer-hole', '111', {}) const tracerNotificationInstance = OpentelemetryNotificationProvider.getTracer('example-tracer-hole', '111', {}) const tracerChat = OpentelemetryChatProvider.getTracer('OpentelemetryChatProvider','some' ,{}) +const tracerUser = OpentelemetryUserProvider.getTracer('OpentelemetryUserProvider','some' ,{}) + + let device: DeviceInfo; Device.getInfo().then(e => { @@ -49,6 +52,8 @@ const createTracingInstance = ({bugPrint, name, module, autoFinish, waitNThrow = _tracerInstance = tracerNotificationInstance } else if (module == 'chat') { _tracerInstance = tracerChat + } else if (module == 'user') { + _tracerInstance = tracerUser } else { _tracerInstance = tracerInstance } @@ -151,7 +156,7 @@ const createTracingInstance = ({bugPrint, name, module, autoFinish, waitNThrow = const duration = Date.now() - (startTime as unknown as number); useCaseDurationHistogram.record(duration, { use_case: name }); - useCaseDurationHistogram.record(duration, { use_case: name, user: SessionStore.user.UserName }); + useCaseDurationHistogram.record(duration, { use_case: name, user: SessionStore.user.FullName || 'No User' }); finish = true }, @@ -161,7 +166,7 @@ const createTracingInstance = ({bugPrint, name, module, autoFinish, waitNThrow = data.errors.push(message) data.status = {code: SpanStatusCode.ERROR, message} span.setStatus({code: SpanStatusCode.ERROR, message}) - Logger.error(message, {...obj, spanId, name}) + Logger.error(message, {...obj, spanId, name, ...data}) }, createSpan: (name, parent?: any) => { return tracerInstance.startSpan(name, { root: false }, parent) as Span; diff --git a/src/app/services/notification/notifications-ends-points.service.ts b/src/app/services/notification/notifications-ends-points.service.ts index 4b218415a..83714710b 100644 --- a/src/app/services/notification/notifications-ends-points.service.ts +++ b/src/app/services/notification/notifications-ends-points.service.ts @@ -16,7 +16,7 @@ export class NotificationsEndsPointsService { postToken(token) { - const headers = { 'Authorization': SessionStore.user.BasicAuthKey }; + // const headers = { 'Authorization': SessionStore.user.BasicAuthKey }; const body = { UserId: SessionStore.user.UserId, TokenId: token, @@ -24,17 +24,17 @@ export class NotificationsEndsPointsService { Service: 1 }; - return this.http.post(`${environment.apiURL}+ 'notifications/token'`, body, { headers }) + return this.http.post(`${environment.apiURL}+ 'notifications/token'`, body, { }) } DeleteToken(token) { const geturl = environment.apiURL + `notifications/token?userId=${SessionStore.user.UserId}&tokenId=${token}`; - const headers = { 'Authorization': SessionStore.user.BasicAuthKey }; + const body = {}; - return this.http.delete(`${geturl}`, { headers, body }) + return this.http.delete(`${geturl}`, { body }) } } diff --git a/src/app/services/notification/notifications-trigger.service.ts b/src/app/services/notification/notifications-trigger.service.ts index 8867bc8bd..8916b151b 100644 --- a/src/app/services/notification/notifications-trigger.service.ts +++ b/src/app/services/notification/notifications-trigger.service.ts @@ -16,55 +16,55 @@ export class NotificationsTriggerService { - sendNotificationWithSend(userID, title, bodymsg, roomId) { - const geturl = environment.apiURL + `notifications/send`; + // sendNotificationWithSend(userID, title, bodymsg, roomId) { + // const geturl = environment.apiURL + `notifications/send`; - const headers = { 'Authorization': SessionStore.user.BasicAuthKey }; - const message = { - "Service": "chat", - "IdObject": roomId - } - let id = 437 - this.http.post(geturl + `?userId=${userID}&title=${title}&body=${bodymsg}`, message, { headers }).subscribe(data => { + // const headers = { 'Authorization': SessionStore.user.BasicAuthKey }; + // const message = { + // "Service": "chat", + // "IdObject": roomId + // } + // let id = 437 + // this.http.post(geturl + `?userId=${userID}&title=${title}&body=${bodymsg}`, message, { headers }).subscribe(data => { - }, (error) => { + // }, (error) => { - }) - } + // }) + // } - ChatSendMessageNotification(userID, title, bodymsg, roomId) { - const geturl = environment.apiURL + `notifications/sendbyUsername`; + // ChatSendMessageNotification(userID, title, bodymsg, roomId) { + // const geturl = environment.apiURL + `notifications/sendbyUsername`; - const headers = { 'Authorization': SessionStore.user.BasicAuthKey }; - const message = { - "Service": "chat", - "IdObject": roomId - } - let id = 437 - this.http.post(geturl + `?username=${userID}&title=${title}&body=${bodymsg}`, message, { headers }).subscribe(data => { - // this.active = true - }, (error) => { + // const headers = { 'Authorization': SessionStore.user.BasicAuthKey }; + // const message = { + // "Service": "chat", + // "IdObject": roomId + // } + // let id = 437 + // this.http.post(geturl + `?username=${userID}&title=${title}&body=${bodymsg}`, message, { headers }).subscribe(data => { + // // this.active = true + // }, (error) => { - }) - } + // }) + // } - ChatSendMessageNotificationGrup(usersID, title, bodymsg, roomId) { - const geturl = environment.apiURL + `notifications/sendByUsernames`; + // ChatSendMessageNotificationGrup(usersID, title, bodymsg, roomId) { + // const geturl = environment.apiURL + `notifications/sendByUsernames`; - const headers = { 'Authorization': SessionStore.user.BasicAuthKey }; - const message = { - "Users": usersID, - "NotificationData": { - "Service": "chat", - "IdObject": roomId - } - } + // const headers = { 'Authorization': SessionStore.user.BasicAuthKey }; + // const message = { + // "Users": usersID, + // "NotificationData": { + // "Service": "chat", + // "IdObject": roomId + // } + // } - this.http.post(geturl + `?title=${title}&body=${bodymsg}`, message, { headers }).subscribe(data => { - // this.active = true - }, (error) => { + // this.http.post(geturl + `?title=${title}&body=${bodymsg}`, message, { headers }).subscribe(data => { + // // this.active = true + // }, (error) => { - }) - } + // }) + // } } diff --git a/src/app/services/notifications.service.ts b/src/app/services/notifications.service.ts index 8c88cd9c8..90fd2a514 100644 --- a/src/app/services/notifications.service.ts +++ b/src/app/services/notifications.service.ts @@ -158,9 +158,9 @@ export class NotificationsService { tracing.setAttribute('outcome', 'success') }, (error) => { - console.error('Permission denied:', error); + tracing.setAttribute('notification.token', 'false') - tracing.setAttribute('outcome', 'failed') + tracing.hasError('Permission denied: request token'); } ); } @@ -168,13 +168,16 @@ export class NotificationsService { DeletePostToken() { - const geturl = environment.apiURL + `notifications/token?userId=${SessionStore.user.UserId}&tokenId=${this.token}`; + if(this.token) { + const geturl = environment.apiURL + `notifications/token?userId=${SessionStore.user.UserId}&tokenId=${this.token}`; - this.DeleteToken(geturl) + this.DeleteToken(geturl) + } + } postToken(token, geturl, tracing: TracingType) { - const headers = { 'Authorization': SessionStore.user.BasicAuthKey }; + //const headers = { 'Authorization': SessionStore.user.BasicAuthKey }; const body = { UserId: SessionStore.user.UserId, TokenId: token, @@ -183,7 +186,7 @@ export class NotificationsService { }; tracing.setAttribute('token.data', token) - this.http.post(`${geturl}`, body, { headers }).subscribe(data => { + this.http.post(`${geturl}`, body, { }).subscribe(data => { this.active = true tracing.setAttribute('outcome','success') tracing.finish() @@ -196,10 +199,10 @@ export class NotificationsService { DeleteToken(geturl) { - const headers = { 'Authorization': SessionStore.user.BasicAuthKey }; + const body = {}; - this.http.delete(`${geturl}`, { headers, body }).subscribe(data => { + this.http.delete(`${geturl}`, { body }).subscribe(data => { this.active = true }, (error) => { @@ -300,57 +303,57 @@ export class NotificationsService { } - sendNotificationWithSend(userID, title, bodymsg, roomId) { - const geturl = environment.apiURL + `notifications/send`; - - const headers = { 'Authorization': SessionStore.user.BasicAuthKey }; - const message = { - "Service": "chat", - "IdObject": roomId - } - let id = 437 - this.http.post(geturl + `?userId=${userID}&title=${title}&body=${bodymsg}`, message, { headers }).subscribe(data => { - this.active = true - }, (error) => { - - }) - } + // sendNotificationWithSend(userID, title, bodymsg, roomId) { + // const geturl = environment.apiURL + `notifications/send`; - ChatSendMessageNotification(userID, title, bodymsg, roomId) { - const geturl = environment.apiURL + `notifications/sendbyUsername`; + // const message = { + // "Service": "chat", + // "IdObject": roomId + // } + // let id = 437 + // this.http.post(geturl + `?userId=${userID}&title=${title}&body=${bodymsg}`, message, { }).subscribe(data => { + // this.active = true + // }, (error) => { - const headers = { 'Authorization': SessionStore.user.BasicAuthKey }; - const message = { - "Service": "chat", - "IdObject": roomId - } - let id = 437 - this.http.post(geturl + `?username=${userID}&title=${title}&body=${bodymsg}`, message, { headers }).subscribe(data => { - this.active = true - }, (error) => { + // }) + // } - }) - } - ChatSendMessageNotificationGrup(usersID, title, bodymsg, roomId) { - const geturl = environment.apiURL + `notifications/sendByUsernames`; + // ChatSendMessageNotification(userID, title, bodymsg, roomId) { + // const geturl = environment.apiURL + `notifications/sendbyUsername`; - const headers = { 'Authorization': SessionStore.user.BasicAuthKey }; - const message = { - "Users": usersID, - "NotificationData": { - "Service": "chat", - "IdObject": roomId - } - } - this.http.post(geturl + `?title=${title}&body=${bodymsg}`, message, { headers }).subscribe(data => { - this.active = true - }, (error) => { + // const message = { + // "Service": "chat", + // "IdObject": roomId + // } + // let id = 437 + // this.http.post(geturl + `?username=${userID}&title=${title}&body=${bodymsg}`, message, { headers }).subscribe(data => { + // this.active = true + // }, (error) => { - }) - } + // }) + // } + + // ChatSendMessageNotificationGrup(usersID, title, bodymsg, roomId) { + // const geturl = environment.apiURL + `notifications/sendByUsernames`; + + // const headers = { 'Authorization': SessionStore.user.BasicAuthKey }; + // const message = { + // "Users": usersID, + // "NotificationData": { + // "Service": "chat", + // "IdObject": roomId + // } + // } + + // this.http.post(geturl + `?title=${title}&body=${bodymsg}`, message, { headers }).subscribe(data => { + // this.active = true + // }, (error) => { + + // }) + // } tempClearArray(data) { this.DataArray = new Array; diff --git a/src/app/services/organic-entity.service.ts b/src/app/services/organic-entity.service.ts index 311887847..4112314ee 100644 --- a/src/app/services/organic-entity.service.ts +++ b/src/app/services/organic-entity.service.ts @@ -4,7 +4,7 @@ import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; import { AuthService } from '../services/auth.service'; -import { LoginUserRespose } from '../models/user.model'; +import { UserSession } from '../models/user.model'; import { OrganicEntity } from 'src/app/models/organic-entity.model'; import { SessionStore } from '../store/session.service'; import { ChangeProfileService } from './change-profile.service'; @@ -15,7 +15,7 @@ import { ChangeProfileService } from './change-profile.service'; export class OrganicEntityService { authheader = {}; - loggeduser: LoginUserRespose; + loggeduser: UserSession; headers: HttpHeaders; constructor( diff --git a/src/app/services/processes.service.ts b/src/app/services/processes.service.ts index c51fc1042..fc5e73ca8 100644 --- a/src/app/services/processes.service.ts +++ b/src/app/services/processes.service.ts @@ -1,6 +1,6 @@ import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; -import { LoginUserRespose } from '../models/user.model'; +import { UserSession } from '../models/user.model'; import { environment } from 'src/environments/environment'; import { Observable } from 'rxjs'; import { DocumentSetUpMeeting } from '../models/CallMeeting'; @@ -16,9 +16,7 @@ import { SessionStore } from '../store/session.service'; export class ProcessesService { authheader = {}; - loggeduser: LoginUserRespose; - headers: HttpHeaders; - headers2: HttpHeaders; + loggeduser: UserSession; @@ -40,17 +38,7 @@ export class ProcessesService { } - setHeader() { - - - this.headers = new HttpHeaders();; - - this.headers = this.headers.set('Authorization', 'Bearer ' + SessionStore.user.Authorization); - - this.headers2 = new HttpHeaders();; - - this.headers2 = this.headers2.set('Authorization', 'Bearer ' + SessionStore.user.Authorization); - } + setHeader() {} uploadFile(formData: any) { @@ -58,7 +46,6 @@ export class ProcessesService { const geturl = environment.apiURL + 'lakefs/UploadFiles'; let options = { - headers: this.headers }; return this.http.post(`${geturl}`, formData, options); @@ -75,7 +62,6 @@ export class ProcessesService { params = params.set("pageSize", "500"); let options = { - headers: this.headers, params: params }; @@ -91,7 +77,7 @@ export class ProcessesService { // params = params.set("userid", userid); // let options = { - // headers: this.headers, + // // params: params // }; @@ -109,7 +95,6 @@ export class ProcessesService { params = params.set("OnlyCount", onlycount.toString()); let options = { - headers: this.headers, params: params }; @@ -124,7 +109,6 @@ export class ProcessesService { params = params.set("serialNumber", serialnumber); let options = { - headers: this.headers, params: params }; return this.http.get(`${geturl}`, options); @@ -138,7 +122,6 @@ export class ProcessesService { /* params = params.set("serialNumber", serialnumber); */ let options = { - headers: this.headers2, /* params: params */ }; return this.http.get(`${geturl}`, options); @@ -151,7 +134,7 @@ export class ProcessesService { /* params = params.set("serialNumber", serialnumber); */ let options = { - headers: this.headers2, + /* params: params */ }; return this.http.put(`${geturl}`, object, options); @@ -164,7 +147,7 @@ export class ProcessesService { params = params.set("serialNumber", serialNumber); let options = { - headers: this.headers, + params: params }; return this.http.post(`${geturl}`, '', options); @@ -177,7 +160,6 @@ export class ProcessesService { params = params.set("onlyCount", onlyCount.toString()); let options = { - headers: this.headers, params: params }; @@ -188,7 +170,7 @@ export class ProcessesService { const geturl = environment.apiURL + 'Tasks/DelegateTask'; let options = { - headers: this.headers, + }; return this.http.post(`${geturl}`, body, options); } @@ -200,7 +182,7 @@ export class ProcessesService { params = params.set("folderId", folderId); let options = { - headers: this.headers, + params: params }; return this.http.get(`${geturl}`, options); @@ -213,7 +195,7 @@ export class ProcessesService { params = params.set("serialNumber", serialnumber); let options = { - headers: this.headers, + params: params }; return this.http.get(`${geturl}`, options); @@ -222,7 +204,7 @@ export class ProcessesService { GetMDOficialTasks(): Observable { const geturl = environment.apiURL + 'tasks/GetMDOficialTasks'; let options = { - headers: this.headers, + }; return this.http.get(`${geturl}`, options); } @@ -230,7 +212,7 @@ export class ProcessesService { GetMDPersonalTasks(): Observable { const geturl = environment.apiURL + 'tasks/GetMDPersonalTasks'; let options = { - headers: this.headers, + }; return this.http.get(`${geturl}`, options); } @@ -243,7 +225,7 @@ export class ProcessesService { params = params.set("onlyCount", count); let options = { - headers: this.headers, + params: params, }; return this.http.get(`${geturl}`, options); @@ -253,7 +235,7 @@ export class ProcessesService { const geturl = environment.apiURL + 'Tasks/Complete'; let options = { - headers: this.headers, + }; return this.http.post(`${geturl}`, body, options) } @@ -262,7 +244,7 @@ export class ProcessesService { const geturl = environment.apiURL + 'presidentialActions/signature'; let options = { - headers: this.headers, + }; return this.http.post(`${geturl}`, body, options) } @@ -273,7 +255,7 @@ export class ProcessesService { const geturl = environment.apiURL + 'Tasks/CompleteTask'; let options = { - headers: this.headers, + }; return this.http.post(`${geturl}`, body, options) } @@ -282,7 +264,7 @@ export class ProcessesService { const geturl = environment.apiURL + 'Tasks/CompleteTaskParecerPr'; let options = { - headers: this.headers, + }; return this.http.post(`${geturl}`, body, options) } @@ -294,7 +276,7 @@ export class ProcessesService { params = params.set("FolderId", FolderId); let options = { - headers: this.headers, + params: params }; return this.http.post(`${geturl}`, '', options); @@ -308,7 +290,7 @@ export class ProcessesService { params = params.set("applicationid", FsId); let options = { - headers: this.headers, + params: params }; return this.http.get(`${geturl}`, options); @@ -317,7 +299,7 @@ export class ProcessesService { postDespatcho(body: any) { const geturl = environment.apiURL + 'Processes/CreateDispatch'; let options = { - headers: this.headers, + }; return this.http.post(`${geturl}`, body, options) } @@ -325,7 +307,7 @@ export class ProcessesService { postDespatchoPr(body: any) { const geturl = environment.apiURL + 'Processes/CreateDispatchPR'; let options = { - headers: this.headers, + }; return this.http.post(`${geturl}`, body, options) } @@ -350,7 +332,7 @@ export class ProcessesService { const geturl = environment.apiURL + 'Processes/CreateParecer'; let options = { - headers: this.headers, + }; return this.http.post(`${geturl}`, body, options) } @@ -374,7 +356,7 @@ export class ProcessesService { const geturl = environment.apiURL + 'Processes/CreateParecerPR'; let options = { - headers: this.headers, + }; return this.http.post(`${geturl}`, body, options) } @@ -382,7 +364,7 @@ export class ProcessesService { postDeferimento(body: any) { const geturl = environment.apiURL + 'Processes/CreateDeferimento'; let options = { - headers: this.headers, + }; return this.http.post(`${geturl}`, body, options) } @@ -390,7 +372,7 @@ export class ProcessesService { GetActionsList() { const geturl = environment.apiURL + 'presidentialActions'; let options = { - headers: this.headers, + }; @@ -400,7 +382,7 @@ export class ProcessesService { GetSubjectType() { const geturl = environment.apiURL + 'ecm/SubjectType'; let options = { - headers: this.headers, + }; return this.http.get(`${geturl}`, options); } @@ -414,7 +396,7 @@ export class ProcessesService { params = params.set("applicationId", FsId); let options = { - headers: this.headers, + params: params }; return this.http.get(`${geturl}`, options); @@ -426,7 +408,7 @@ export class ProcessesService { url = url.replace('/V4/', '/V5/') let options: any = { - headers: this.headers, + } return this.http.post(`${url}`, body, options); } @@ -442,7 +424,7 @@ export class ProcessesService { params = params.set("SourceLocation ", 17); let options = { - headers: this.headers, + params: params }; return this.http.get(`${geturl}`, options); @@ -456,7 +438,7 @@ export class ProcessesService { params = params.set("docid", DocId); let options: any = { - headers: this.headers, + params } @@ -474,7 +456,7 @@ export class ProcessesService { params = params.set("applicationId", FsId); let options = { - headers: this.headers, + params: params }; return this.http.get(`${geturl}`, options); @@ -484,7 +466,7 @@ export class ProcessesService { const geturl = environment.apiURL + 'Tasks/AttachDocImage'; let options = { - headers: this.headers, + }; return this.http.post(`${geturl}`, file, options); } @@ -495,7 +477,7 @@ export class ProcessesService { let params = new HttpParams(); params = params.set('calendarName', calendarType); let options = { - headers: this.headers, + params: params }; return this.http.post(`${geturl}`, body, options); diff --git a/src/app/services/publications.service.ts b/src/app/services/publications.service.ts index 30182c8d1..e39833619 100644 --- a/src/app/services/publications.service.ts +++ b/src/app/services/publications.service.ts @@ -2,7 +2,7 @@ import { Injectable, OnInit } from '@angular/core'; import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { environment } from 'src/environments/environment'; import { AuthService } from '../services/auth.service'; -import { LoginUserRespose } from '../models/user.model'; +import { UserSession } from '../models/user.model'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators' import { Publication } from '../models/publication'; @@ -19,7 +19,7 @@ export class PublicationsService { authheader = {}; - loggeduser: LoginUserRespose; + loggeduser: UserSession; headers: HttpHeaders; constructor(private http: HttpClient, user: AuthService, diff --git a/src/app/services/search.service.ts b/src/app/services/search.service.ts index 47713c2c3..4ed674ad6 100644 --- a/src/app/services/search.service.ts +++ b/src/app/services/search.service.ts @@ -4,7 +4,7 @@ import { Event } from '../models/event.model'; import { from, Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; import { AuthService } from '../services/auth.service'; -import { LoginUserRespose } from '../models/user.model'; +import { UserSession } from '../models/user.model'; import { EventSearch } from "src/app/models/event-search"; import { TopSearch } from 'src/app/models/top-search'; import { SessionStore } from '../store/session.service'; @@ -16,7 +16,7 @@ import { ChangeProfileService } from './change-profile.service'; export class SearchService { // state authheader = {}; - loggeduser: LoginUserRespose; + loggeduser: UserSession; headers: HttpHeaders; categories= Array; diff --git a/src/app/services/task.service.ts b/src/app/services/task.service.ts index 7a2bba8c2..07ebe69ca 100644 --- a/src/app/services/task.service.ts +++ b/src/app/services/task.service.ts @@ -203,7 +203,6 @@ export class TaskService { try { await this.loadExpedientes() this.loadCount = true; - } catch(error) { this.loadCount = true; } diff --git a/src/app/shared/API/middleware/middleware-service.service.ts b/src/app/shared/API/middleware/middleware-service.service.ts index 78196de22..296ab101a 100644 --- a/src/app/shared/API/middleware/middleware-service.service.ts +++ b/src/app/shared/API/middleware/middleware-service.service.ts @@ -4,10 +4,11 @@ import { HttpServiceService } from 'src/app/services/http/http-service.service'; import { Observable} from 'rxjs'; import { CreateEvent, EditEvent, EventDetailsDTO, EventsDTO, IuploadFileLK, refreshTokenDTO } from "./interface"; import { HttpClient, HttpEvent, HttpHeaders, HttpParams } from '@angular/common/http'; -import { DetectCalendars, makeHeaderForCalendar } from '../../utils/utils'; import { z } from "zod"; import { ok, err } from 'neverthrow'; import { SessionStore } from 'src/app/store/session.service'; +import { UserService } from 'src/app/module/user/domain/user.service' + /* import { ok, err } from 'neverthrow'; */ @@ -19,122 +20,114 @@ export class MiddlewareServiceService { constructor( private HttpServiceService: HttpServiceService, private http: HttpClient, + private UserService:UserService ) { window["MiddlewareServiceService"] = this } - refreshToken(refreshToken: string) { - const data = { - refreshToken: refreshToken - } - - return this.HttpServiceService.put(environment.apiURL + "UserAuthentication/RefreshToken", data, {}) - // .pipe( - // map((response: HttpResponse) => { - // return response.body - // }) - // ); - } + // refreshToken(refreshToken: string) { + // this.UserService.refreshToken() + // } // ================================ Calendar ================================================= - GetEvents(startDate: string, endDate: string, calendarId): Observable { + // GetEvents(startDate: string, endDate: string, calendarId): Observable { - let geturl = environment.apiURL + 'calendar/GetEvents'; - geturl = geturl.replace('/V4/', '/V5/') + // let geturl = environment.apiURL + 'calendar/GetEvents'; + // geturl = geturl.replace('/V4/', '/V5/') - let params = new HttpParams(); + // let params = new HttpParams(); - params = params.set("StartDate", startDate); - params = params.set("EndDate", endDate); + // params = params.set("StartDate", startDate); + // params = params.set("EndDate", endDate); - const calendar = DetectCalendars(calendarId) - const header = makeHeaderForCalendar(calendar) + // const calendar = DetectCalendars(calendarId) + // const header = makeHeaderForCalendar(calendar) - let options = { - headers: header, - params: params - }; + // let options = { + // headers: header, + // params: params + // }; - // return this.HttpServiceService.get(`${geturl}`, options); + // // return this.HttpServiceService.get(`${geturl}`, options); - return {} as any - } + // return {} as any + // } - GetEventDetail(eventId: string, calendarId: string) { - let geturl = environment.apiURL + 'calendar/GetEvent'; - let params = new HttpParams(); + // GetEventDetail(eventId: string, calendarId: string) { + // let geturl = environment.apiURL + 'calendar/GetEvent'; + // let params = new HttpParams(); - params = params.set("EventId", eventId); + // params = params.set("EventId", eventId); - const calendar = DetectCalendars(calendarId) - const header = makeHeaderForCalendar(calendar) + // const calendar = DetectCalendars(calendarId) + // const header = makeHeaderForCalendar(calendar) - let options = { - headers: header, - params: params - } - return this.HttpServiceService.get(`${geturl}`, options); - } + // let options = { + // headers: header, + // params: params + // } + // return this.HttpServiceService.get(`${geturl}`, options); + // } - createEvent(event: CreateEvent, calendarName: string, CalendarId) { - const puturl = environment.apiURL + 'Calendar/PostEvent'; - let params = new HttpParams(); + // createEvent(event: CreateEvent, calendarName: string, CalendarId) { + // const puturl = environment.apiURL + 'Calendar/PostEvent'; + // let params = new HttpParams(); - if(!event.TimeZone) { - const now = new Date(); - event.TimeZone = event.TimeZone = now.toString().match(/([A-Z]+[\+-][0-9]+.*)/)[1]; - } + // if(!event.TimeZone) { + // const now = new Date(); + // event.TimeZone = event.TimeZone = now.toString().match(/([A-Z]+[\+-][0-9]+.*)/)[1]; + // } - if(!event.Organizer) { - event.Organizer = { - "Id": SessionStore.user.UserId, - "EmailAddress": SessionStore.user.Email, - "Name": SessionStore.user.UserName, - "IsRequired": true, - "UserType": "GD" - } - } + // if(!event.Organizer) { + // event.Organizer = { + // "Id": SessionStore.user.UserId, + // "EmailAddress": SessionStore.user.Email, + // "Name": SessionStore.user.UserName, + // "IsRequired": true, + // "UserType": "GD" + // } + // } - params = params.set("CalendarName", calendarName); - params = params.set("notifyUsers", true) + // params = params.set("CalendarName", calendarName); + // params = params.set("notifyUsers", true) - let options: any; + // let options: any; - const calendar = DetectCalendars(CalendarId) - const header = makeHeaderForCalendar(calendar) + // const calendar = DetectCalendars(CalendarId) + // const header = makeHeaderForCalendar(calendar) - options = { - headers: header, - params: params - }; + // options = { + // headers: header, + // params: params + // }; - return this.HttpServiceService.post(`${puturl}`, event, options) - } + // return this.HttpServiceService.post(`${puturl}`, event, options) + // } - editEvent(event: EditEvent, conflictResolutionMode: number, sendInvitationsOrCancellationsMode: number, CalendarId? ) { + // editEvent(event: EditEvent, conflictResolutionMode: number, sendInvitationsOrCancellationsMode: number, CalendarId? ) { - let options: any; + // let options: any; - const calendar = DetectCalendars(CalendarId) - const header = makeHeaderForCalendar(calendar) - let params = new HttpParams(); + // const calendar = DetectCalendars(CalendarId) + // const header = makeHeaderForCalendar(calendar) + // let params = new HttpParams(); - params = params.set("conflictResolutionMode", conflictResolutionMode.toString()); - params = params.set("sendInvitationsOrCancellationsMode", sendInvitationsOrCancellationsMode.toString()); - params.set('CalendarId', event.CalendarId) - params.set('CalendarName', event.CalendarName) + // params = params.set("conflictResolutionMode", conflictResolutionMode.toString()); + // params = params.set("sendInvitationsOrCancellationsMode", sendInvitationsOrCancellationsMode.toString()); + // params.set('CalendarId', event.CalendarId) + // params.set('CalendarName', event.CalendarName) - options = { - headers: header, - params: params - }; + // options = { + // headers: header, + // params: params + // }; - const putUrl = environment.apiURL + 'calendar/PutEvent'; - return this.HttpServiceService.put(`${putUrl}`, event, options); + // const putUrl = environment.apiURL + 'calendar/PutEvent'; + // return this.HttpServiceService.put(`${putUrl}`, event, options); - } + // } // ================================ Acções ================================================= diff --git a/src/app/shared/event/attendee-modal/attendee-modal.page.ts b/src/app/shared/event/attendee-modal/attendee-modal.page.ts index c5591e71e..a4b25356f 100644 --- a/src/app/shared/event/attendee-modal/attendee-modal.page.ts +++ b/src/app/shared/event/attendee-modal/attendee-modal.page.ts @@ -4,7 +4,7 @@ import { removeDuplicate } from 'src/plugin/removeDuplicate.js' import { ThemeService } from 'src/app/services/theme.service' import { ViewChild } from '@angular/core'; import { Searchbar } from 'ionic-angular'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { SessionStore } from 'src/app/store/session.service'; import { Router } from '@angular/router'; import { ContactRepositoryService } from 'src/app/services/Repositorys/contacts/repository/contacts-repository.service'; @@ -46,7 +46,7 @@ export class AttendeePage implements OnInit { LtaskParticipants: EventPerson[] = []; LtaskParticipantsCc: EventPerson[] = []; - loggeduser: LoginUserRespose; + loggeduser: UserSession; listOfNotAllowdRoute = ['/home/gabinete-digital/despachos/', ] selectedUserCalendar:any; diff --git a/src/app/shared/gabinete-digital/all-processes/all-processes.page.ts b/src/app/shared/gabinete-digital/all-processes/all-processes.page.ts index ca65a4eca..59adf69ea 100644 --- a/src/app/shared/gabinete-digital/all-processes/all-processes.page.ts +++ b/src/app/shared/gabinete-digital/all-processes/all-processes.page.ts @@ -1,6 +1,6 @@ import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core'; import { NavigationEnd, Router } from '@angular/router'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { ThemeService } from 'src/app/services/theme.service'; import { TaskService } from 'src/app/services/task.service'; @@ -13,7 +13,7 @@ import { TaskService } from 'src/app/services/task.service'; export class AllProcessesPage implements OnInit { skeletonLoader = false; - loggeduser: LoginUserRespose; + loggeduser: UserSession; hideSearchBtn: boolean = false; showSearch = false; searchSubject: string = ''; diff --git a/src/app/shared/gabinete-digital/despachos-pr/despachos-pr.page.ts b/src/app/shared/gabinete-digital/despachos-pr/despachos-pr.page.ts index e0b411ae8..7d4ed8ece 100644 --- a/src/app/shared/gabinete-digital/despachos-pr/despachos-pr.page.ts +++ b/src/app/shared/gabinete-digital/despachos-pr/despachos-pr.page.ts @@ -1,6 +1,6 @@ import { Component, OnInit} from '@angular/core'; import { customTask} from '../../../models/dailyworktask.model'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { NavigationStart, Router } from '@angular/router'; import { DespachosprStore } from 'src/app/store/despachospr-store.service'; import { CustomTaskPipe } from 'src/app/pipes/custom-task.pipe'; @@ -20,7 +20,7 @@ export class DespachosPrPage implements OnInit { customTaskPipe = new CustomTaskPipe() skeletonLoader = false - loggeduser: LoginUserRespose; + loggeduser: UserSession; despachosprstore = DespachosprStore; environment = environment filterName: 'Para hoje' | 'Novos'| 'Lidos'| 'Não lidos'| 'OverdueTasks' | 'Todos' = 'Todos' diff --git a/src/app/shared/gabinete-digital/expedientes-pr/expedientes-pr.page.ts b/src/app/shared/gabinete-digital/expedientes-pr/expedientes-pr.page.ts index 68d2d58f6..284176700 100644 --- a/src/app/shared/gabinete-digital/expedientes-pr/expedientes-pr.page.ts +++ b/src/app/shared/gabinete-digital/expedientes-pr/expedientes-pr.page.ts @@ -1,7 +1,7 @@ import { Component, EventEmitter, OnInit, Output } from '@angular/core'; import { NavigationStart, Router } from '@angular/router'; import { ProcessesService } from 'src/app/services/processes.service'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { CustomTaskPipe } from 'src/app/pipes/custom-task.pipe'; import { ExpedienteGdStore } from 'src/app/store/expedientegd-store.service'; import { ExpedienteTaskPipe } from 'src/app/pipes/expediente-task.pipe'; @@ -25,7 +25,7 @@ export class ExpedientesPrPage implements OnInit { customTaskPipe = new CustomTaskPipe() expedienteTaskPipe = new ExpedienteTaskPipe() - loggeduser: LoginUserRespose; + loggeduser: UserSession; filterName: 'Para hoje' | 'Novos'| 'Lidos'| 'Não lidos'| 'OverdueTasks' | 'Todos' = 'Todos' showSearch = false diff --git a/src/app/shared/gabinete-digital/generic/task-details/task-details.page.ts b/src/app/shared/gabinete-digital/generic/task-details/task-details.page.ts index b03e2940b..14ffab848 100644 --- a/src/app/shared/gabinete-digital/generic/task-details/task-details.page.ts +++ b/src/app/shared/gabinete-digital/generic/task-details/task-details.page.ts @@ -9,7 +9,7 @@ import { ModalController } from '@ionic/angular'; import { DocumentSetUpMeetingPage } from 'src/app/modals/document-set-up-meeting/document-set-up-meeting.page'; import { HeaderSettingsService } from "src/app/services/header-settings.service" import { SessionStore } from 'src/app/store/session.service'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; @@ -33,7 +33,7 @@ export class TaskDetailsPage implements OnInit { selectedIndex = 0 dropButton = true - loggeduser: LoginUserRespose; + loggeduser: UserSession; @ViewChild('text', { static: false }) text: ElementRef; constructor( @@ -48,20 +48,10 @@ export class TaskDetailsPage implements OnInit { this.DeviceService.isDesktop(); this.loggeduser = SessionStore.user - - // if(this.task.Note) { - // this.task.Note = this.sanitizeHtml(this.task.Note) as any - // } - - // if(this.fulltask?.workflowInstanceDataFields?.TaskMessage) { - // this.fulltask.workflowInstanceDataFields.TaskMessage = this.sanitizeHtml(this.fulltask.workflowInstanceDataFields.TaskMessage); - // } - - setTimeout(() => { console.log('change', this.task.Note); // this.task.Note = this.sanitizeHtml(this.task.Note) as any - if(this.text.nativeElement) { + if(this.text?.nativeElement) { (this.text.nativeElement as HTMLDivElement).innerHTML = this.decode(this.task.Note) } @@ -71,7 +61,7 @@ export class TaskDetailsPage implements OnInit { setTimeout(() => { console.log('change', this.task.Note); // this.task.Note = this.sanitizeHtml(this.task.Note) as any - if(this.text.nativeElement) { + if(this.text?.nativeElement) { (this.text.nativeElement as HTMLDivElement).innerHTML = this.decode(this.task.Note) } @@ -80,7 +70,7 @@ export class TaskDetailsPage implements OnInit { setTimeout(() => { console.log('change', this.task.Note); // this.task.Note = this.sanitizeHtml(this.task.Note) as any - if(this.text.nativeElement) { + if(this.text?.nativeElement) { (this.text.nativeElement as HTMLDivElement).innerHTML = this.decode(this.task.Note) } @@ -89,7 +79,7 @@ export class TaskDetailsPage implements OnInit { setTimeout(() => { console.log('change', this.task.Note); // this.task.Note = this.sanitizeHtml(this.task.Note) as any - if(this.text.nativeElement) { + if(this.text?.nativeElement) { (this.text.nativeElement as HTMLDivElement).innerHTML = this.decode(this.task.Note) } @@ -98,7 +88,7 @@ export class TaskDetailsPage implements OnInit { setTimeout(() => { console.log('change', this.task.Note); // this.task.Note = this.sanitizeHtml(this.task.Note) as any - if(this.text.nativeElement) { + if(this.text?.nativeElement) { (this.text.nativeElement as HTMLDivElement).innerHTML = this.decode(this.task.Note) } @@ -108,7 +98,7 @@ export class TaskDetailsPage implements OnInit { setTimeout(() => { console.log('change', this.task.Note); // this.task.Note = this.sanitizeHtml(this.task.Note) as any - if(this.text.nativeElement) { + if(this.text?.nativeElement) { (this.text.nativeElement as HTMLDivElement).innerHTML = this.decode(this.task.Note) } @@ -185,7 +175,7 @@ export class TaskDetailsPage implements OnInit { classs = 'modal modal-desktop showAsideOptions' } // check passing - console.log('this.Document----------openExpedientActionsModal', Document) + console.log('this.Document----------openExpedientActionsModal', Document, this.fulltask) const modal = await this.modalController.create({ component: ExpedientTaskModalPage, componentProps: { diff --git a/src/app/shared/gabinete-digital/pendentes/pendentes.page.ts b/src/app/shared/gabinete-digital/pendentes/pendentes.page.ts index be4244646..1d155ab61 100644 --- a/src/app/shared/gabinete-digital/pendentes/pendentes.page.ts +++ b/src/app/shared/gabinete-digital/pendentes/pendentes.page.ts @@ -4,7 +4,7 @@ import { removeDuplicate } from 'src/plugin/removeDuplicate.js' import { customTask} from '../../../models/dailyworktask.model'; import { ProcessesService } from 'src/app/services/processes.service'; import { PendentesStore } from 'src/app/store/pendestes-store.service'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { CustomTaskPipe } from 'src/app/pipes/custom-task.pipe'; import { SortService } from 'src/app/services/functions/sort.service'; import { Storage } from '@ionic/storage'; @@ -22,7 +22,7 @@ export class PendentesPage implements OnInit { skeletonLoader: boolean = false; pendentesstore = PendentesStore; customTaskPipe = new CustomTaskPipe() - loggeduser: LoginUserRespose; + loggeduser: UserSession; listToPresent = []; @Input() profile:string; diff --git a/src/app/shared/popover/despachos-pr-options/despachos-pr-options.page.html b/src/app/shared/popover/despachos-pr-options/despachos-pr-options.page.html index 0fed74a4a..e18ea8cb7 100644 --- a/src/app/shared/popover/despachos-pr-options/despachos-pr-options.page.html +++ b/src/app/shared/popover/despachos-pr-options/despachos-pr-options.page.html @@ -26,7 +26,7 @@
- + diff --git a/src/app/shared/popover/despachos-pr-options/despachos-pr-options.page.ts b/src/app/shared/popover/despachos-pr-options/despachos-pr-options.page.ts index db80a4bc6..5b317b8fb 100644 --- a/src/app/shared/popover/despachos-pr-options/despachos-pr-options.page.ts +++ b/src/app/shared/popover/despachos-pr-options/despachos-pr-options.page.ts @@ -54,7 +54,7 @@ export class DespachosPrOptionsPage implements OnInit { this.activatedRoute.queryParams.subscribe(params => { if(params["serialNumber"]) { this.serialNumber = params["serialNumber"]; - + } }); @@ -91,9 +91,9 @@ export class DespachosPrOptionsPage implements OnInit { }); modal.onDidDismiss().then( (res)=> { - + if(res['data']=='openDiscart') { - + this.distartExpedientModal(); @@ -113,7 +113,7 @@ export class DespachosPrOptionsPage implements OnInit { sendExpedienteToPending() { const loader = this.toastService.loading() this.processes.SetTaskToPending(this.serialNumber).subscribe(res=>{ - + this.httpErroHandle.httpsSucessMessagge('Enviar para Pendentes') this.popoverController.dismiss('close') loader.remove() @@ -122,7 +122,7 @@ export class DespachosPrOptionsPage implements OnInit { if(error.status == 0) { this.toastService._badRequest('Sem acesso à internet. Por favor verifique sua conexão') } else { - + this.toastService._badRequest('Processo não encontrado') } }); @@ -130,7 +130,7 @@ export class DespachosPrOptionsPage implements OnInit { async distartExpedientModal() { this.popoverController.dismiss(); - + const modal = await this.modalController.create({ component: DiscartExpedientModalPage, componentProps: { @@ -145,7 +145,7 @@ export class DespachosPrOptionsPage implements OnInit { modal.onDidDismiss().then(res=>{ if(res['data']=='close'){ this.close(); - /* + /* this.close(); this.openMenu(); */ } @@ -241,7 +241,7 @@ export class DespachosPrOptionsPage implements OnInit { if(error.status == 0) { this.toastService._badRequest('Sem acesso à internet. Por favor verifique sua conexão') } else { - + this.toastService._badRequest() } } finally { @@ -269,7 +269,7 @@ export class DespachosPrOptionsPage implements OnInit { }); modal.onDidDismiss().then(async (res) => { - + if(res.data){ @@ -300,6 +300,8 @@ export class DespachosPrOptionsPage implements OnInit { } else if(actionName == 'Concluido') { await this.concluir(res.data.note, docs); + } else if (actionName == 'Executado1') { + await this.executadoPR(res.data.note, docs) } this.goBack(); @@ -333,7 +335,7 @@ export class DespachosPrOptionsPage implements OnInit { if(error.status == 0) { this.toastService._badRequest('Sem acesso à internet. Por favor verifique sua conexão') } else { - + this.toastService._badRequest() } } @@ -395,6 +397,33 @@ export class DespachosPrOptionsPage implements OnInit { } + // Pr dispacho criado por mim, tarefa de concluir despacho saida Marcar como concluida + async executadoPR(note:string, documents:any) { + let body = { + "serialNumber": this.serialNumber, + "action": "Executado", + "ActionTypeId": 95, + "dataFields": { + "ReviewUserComment": note, + }, + "AttachmentList" :documents, + } + + const loader = this.toastService.loading() + + try { + await this.processes.CompleteTask(body).toPromise() + this.httpErroHandle.httpsSucessMessagge('Executado') + this.close(); + this.toastService.successMessage() + } catch(error) { + this.toastService.badRequest() + } finally { + loader.remove() + } + + } + async reexecutar(note:string, documents:any){ let body = { diff --git a/src/app/shared/popover/opts-expediente-pr/opts-expediente-pr.page.ts b/src/app/shared/popover/opts-expediente-pr/opts-expediente-pr.page.ts index 098126e26..62f81c75b 100644 --- a/src/app/shared/popover/opts-expediente-pr/opts-expediente-pr.page.ts +++ b/src/app/shared/popover/opts-expediente-pr/opts-expediente-pr.page.ts @@ -2,7 +2,7 @@ import { Component, OnInit } from '@angular/core'; import { ModalController, NavParams, PopoverController } from '@ionic/angular'; import { AddNotePage } from 'src/app/modals/add-note/add-note.page'; import { SearchList } from 'src/app/models/search-document'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { DiscartExpedientModalPage } from 'src/app/pages/gabinete-digital/discart-expedient-modal/discart-expedient-modal.page'; import { BookMeetingModalPage } from 'src/app/pages/gabinete-digital/expediente/book-meeting-modal/book-meeting-modal.page'; import { ExpedientTaskModalPage } from 'src/app/pages/gabinete-digital/expediente/expedient-task-modal/expedient-task-modal.page'; @@ -40,7 +40,7 @@ export class OptsExpedientePrPage implements OnInit { showEnviarPendentes = false; - loggeduser: LoginUserRespose; + loggeduser: UserSession; constructor( private popoverController: PopoverController, diff --git a/src/app/shared/utils/utils.ts b/src/app/shared/utils/utils.ts index 3d05c7d8c..1289102e0 100644 --- a/src/app/shared/utils/utils.ts +++ b/src/app/shared/utils/utils.ts @@ -2,16 +2,16 @@ import { HttpHeaders } from "@angular/common/http"; import { calendarInterface } from "src/app/models/user.model"; import { SessionStore } from "src/app/store/session.service"; -export function DetectCalendars(CalendarId) { - const calendars = SessionStore.user.OwnerCalendars.concat(SessionStore.user.SharedCalendars) - return calendars.find((e) => e.CalendarId == CalendarId) -} +// export function DetectCalendars(CalendarId) { +// const calendars = SessionStore.user.OwnerCalendars.concat(SessionStore.user.SharedCalendars) +// return calendars.find((e) => e.CalendarId == CalendarId) +// } -export function makeHeaderForCalendar(calendar: calendarInterface) { - let header = new HttpHeaders();; - header = header.set('Authorization', 'Bearer ' + SessionStore.user.Authorization); - header = header.set('CalendarId', calendar.CalendarId); - header = header.set('CalendarRoleId', calendar.CalendarRoleId); - header = header.set('CalendarName', calendar.CalendarName); - return header -} +// export function makeHeaderForCalendar(calendar: calendarInterface) { +// let header = new HttpHeaders();; +// header = header.set('Authorization', 'Bearer ' + SessionStore.user.Authorization); +// header = header.set('CalendarId', calendar.CalendarId); +// header = header.set('CalendarRoleId', calendar.CalendarRoleId); +// header = header.set('CalendarName', calendar.CalendarName); +// return header +// } diff --git a/src/app/store/session.service.ts b/src/app/store/session.service.ts index 965389ecf..7cdf352d5 100644 --- a/src/app/store/session.service.ts +++ b/src/app/store/session.service.ts @@ -15,31 +15,6 @@ class SessionService { private keyName: string; forceToLoginWithForceToLogInWithPassword = false - - permission = { - Agenda: { - access: false - }, - Gabinete: { - access: false, - pr_tasks: false, - md_tasks: false, - aprove_event: false - }, - Actions: { - access : false, - create : false, - delete : false, - edit : false, - createPost : false, - deletePost : false, - editPost : false - }, - Chat: { - access: false - } - } - hasPassLogin = false constructor() { @@ -122,6 +97,21 @@ class SessionService { } reset(user) { + + if(user.RoleID) { + if (user.RoleID == 100000014) { + user.Profile = 'PR' + } else if (user.RoleID == 100000011) { + user.Profile = 'MDGPR' + } else if (user.RoleID == 99999872) { + user.Profile = 'Consultant' + } else if (user.RoleID == 99999886) { + user.Profile = 'SGGPR' + } else { + user.Profile = 'Unknown' + } + } + this._user = user this.setInativity(true) @@ -153,44 +143,15 @@ class SessionService { } - get getManagerInitials() { - let names = this._user.ManagerName.split(' ') || ' ', - initials = names[0].substring(0, 1).toUpperCase(); - if (names.length > 1) { - initials += names[names.length - 1].substring(0, 1).toUpperCase(); - } + // get getManagerInitials() { + // let names = this._user.ManagerName.split(' ') || ' ', + // initials = names[0].substring(0, 1).toUpperCase(); + // if (names.length > 1) { + // initials += names[names.length - 1].substring(0, 1).toUpperCase(); + // } - return initials; - } - - - clearPermission() { - this.permission = { - Agenda: { - access: false - }, - Gabinete: { - access: false, - pr_tasks: false, - md_tasks: false, - aprove_event: false - }, - Actions: { - access : false, - create : false, - delete : false, - edit : false, - createPost : false, - deletePost : false, - editPost : false - }, - Chat: { - access: false - } - } - } - - setPermission() {} + // return initials; + // } } diff --git a/src/app/ui/agenda/agenda.page.html b/src/app/ui/agenda/agenda.page.html index c409d23db..fc89766f6 100644 --- a/src/app/ui/agenda/agenda.page.html +++ b/src/app/ui/agenda/agenda.page.html @@ -416,7 +416,7 @@ [serialNumber] = "eventToaprove.serialNumber" [InstanceId] = "eventToaprove.InstanceId" [saveData] = "eventToaprove.saveData" - (cloneAllmobileComponent)="viewEventDetailDismiss($event)" + (viewEventDetailDismiss)="viewEventDetailDismiss($event)" (closeEventToApprove)="closeEventToApproveGoBack()" (AproveEventEditEvent)="AproveEventEditEvent($event)" (EditApproveEventDismiss)="EditApproveEventDismiss()" diff --git a/src/app/ui/agenda/agenda.page.ts b/src/app/ui/agenda/agenda.page.ts index 68f8145f7..daf45a632 100644 --- a/src/app/ui/agenda/agenda.page.ts +++ b/src/app/ui/agenda/agenda.page.ts @@ -18,7 +18,7 @@ import { } from 'angular-calendar'; import { CustomDateFormatter } from './custom-date-formatter.provider'; import { NewEventPage } from './modal/new-event/new-event.page'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { DateAdapter } from '@angular/material/core'; import { eventSource } from 'src/app/models/agenda/eventSource'; import { CalendarStore } from 'src/app/store/calendar.service'; @@ -166,7 +166,7 @@ export class AgendaPage implements OnInit { */ IsEvent: "edit" | "add" | "view"; viewingEventObject: CalendarEvent; - loggeduser: LoginUserRespose; + loggeduser: UserSession; monthNum; yearNum; diff --git a/src/app/ui/agenda/component/edit-event-to-approve/edit-event-to-approve.page.ts b/src/app/ui/agenda/component/edit-event-to-approve/edit-event-to-approve.page.ts index 509bf5487..44cc56869 100644 --- a/src/app/ui/agenda/component/edit-event-to-approve/edit-event-to-approve.page.ts +++ b/src/app/ui/agenda/component/edit-event-to-approve/edit-event-to-approve.page.ts @@ -143,7 +143,6 @@ export class EditEventToApprovePage implements OnInit { } ngOnInit() { - console.log('here!!!') if (this.restoreTemporaryData()) { this.setOtherData() } else { @@ -158,7 +157,7 @@ export class EditEventToApprovePage implements OnInit { @XTracerAsync({name:'edit-event-approve/getTask', bugPrint: true}) async getTask(tracing?: TracingType) { - const res = await this.agendaDataRepository.getEventToApproveById(this.serialNumber) + const res = await this.agendaDataRepository.getEventToApproveById(this.serialNumber, tracing) if(res.isOk()) { console.log('evento to apro to edit', res.value) this.eventProcess = res.value as any; diff --git a/src/app/ui/agenda/component/event-list/event-list.page.scss b/src/app/ui/agenda/component/event-list/event-list.page.scss index 1b56f0a3f..22042b663 100644 --- a/src/app/ui/agenda/component/event-list/event-list.page.scss +++ b/src/app/ui/agenda/component/event-list/event-list.page.scss @@ -1,6 +1,7 @@ @import '~src/function.scss'; :host{ margin: 0; + background-color: white; } .header-content{ overflow: auto; diff --git a/src/app/ui/agenda/component/event-list/event-list.page.ts b/src/app/ui/agenda/component/event-list/event-list.page.ts index 9e2db6afc..2c36ac837 100644 --- a/src/app/ui/agenda/component/event-list/event-list.page.ts +++ b/src/app/ui/agenda/component/event-list/event-list.page.ts @@ -3,7 +3,7 @@ import { EventBody } from 'src/app/models/eventbody.model'; import { EventPerson } from 'src/app/models/eventperson.model'; import { ProcessesService } from 'src/app/services/processes.service'; import { NavigationEnd, Router } from '@angular/router'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { SortService } from 'src/app/services/functions/sort.service'; import { SessionStore } from 'src/app/store/session.service'; import { EventoAprovacaoStore } from 'src/app/store/eventoaprovacao-store.service'; @@ -33,7 +33,7 @@ export class EventListPage implements OnInit { eventBody: EventBody; categories: string[]; serialnumber:string; - loggeduser: LoginUserRespose; + loggeduser: UserSession; segment:string; eventoaprovacaostore = EventoAprovacaoStore; environment = environment @@ -184,12 +184,22 @@ export class EventListPage implements OnInit { } async openApproveModal(eventSerialNumber, data) { - + if (window.innerWidth <= 1024) { + if (this.router.url == '/home/agenda/event-list') { + this.router.navigate(['/home/agenda/event-list/approve-event', eventSerialNumber, 'agenda']) + } + else if (this.router.url == '/home/gabinete-digital/event-list') { + this.router.navigate(['/home/gabinete-digital/event-list/approve-event', eventSerialNumber, 'gabinete-digital']) + } + } + else { this.approveEventDismiss.emit({ - "serialNumber": eventSerialNumber, - "action": "Aprovar", - "saveData": data - }); + "serialNumber": eventSerialNumber, + "action": "Aprovar", + "saveData": data + }); + } + } refreshing() { diff --git a/src/app/ui/agenda/component/new-event/new-event.page.ts b/src/app/ui/agenda/component/new-event/new-event.page.ts index 1eb3a3084..51f6d439a 100644 --- a/src/app/ui/agenda/component/new-event/new-event.page.ts +++ b/src/app/ui/agenda/component/new-event/new-event.page.ts @@ -5,7 +5,7 @@ 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 { UserSession } from 'src/app/models/user.model'; import { DateAdapter } from '@angular/material/core'; import * as _moment from 'moment'; import * as _rollupMoment from 'moment'; @@ -89,7 +89,7 @@ export class NewEventPage implements OnInit { documents: SearchList_v2[] = []; - loggeduser: LoginUserRespose; + loggeduser: UserSession; Form: FormGroup; diff --git a/src/app/ui/agenda/modal/new-event/new-event.page.ts b/src/app/ui/agenda/modal/new-event/new-event.page.ts index 0781801e8..f8571d09c 100644 --- a/src/app/ui/agenda/modal/new-event/new-event.page.ts +++ b/src/app/ui/agenda/modal/new-event/new-event.page.ts @@ -3,7 +3,7 @@ import { ModalController, NavParams, Platform } from '@ionic/angular'; import { EventBody } from 'src/app/models/eventbody.model'; import { EventPerson } from 'src/app/models/eventperson.model'; import { SearchList } from 'src/app/models/search-document'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { ToastService } from 'src/app/services/toast.service'; import { Event } from '../../../../models/event.model'; import { AttendeesPageModal } from '../../../../pages/events/attendees/attendees.page'; @@ -94,7 +94,7 @@ export class NewEventPage implements OnInit { documents: SearchList[] = []; - loggeduser: LoginUserRespose; + loggeduser: UserSession; members: any; CalendarName; SessionStore = SessionStore; diff --git a/src/app/ui/chat/chat.page.html b/src/app/ui/chat/chat.page.html index 0681d79d6..b7925d976 100644 --- a/src/app/ui/chat/chat.page.html +++ b/src/app/ui/chat/chat.page.html @@ -12,6 +12,17 @@
Chat +
@@ -41,7 +52,7 @@
diff --git a/src/app/ui/chat/chat.page.ts b/src/app/ui/chat/chat.page.ts index a2ba466ed..d35d49df7 100644 --- a/src/app/ui/chat/chat.page.ts +++ b/src/app/ui/chat/chat.page.ts @@ -62,6 +62,9 @@ export class ChatPage implements OnInit { //items$!: DexieObservable; items$!: Observable; rooms: RoomViewModel[] = []; + filterRoomList: RoomViewModel[] = []; + roomName = '' + private subscription: Subscription; expirationDate = {} private intervalSubscription: Subscription; @@ -119,7 +122,17 @@ export class ChatPage implements OnInit { ); // this.RoomSelected = this.rooms.filter(e => e.id == this.selectedRoomId)[0] + this.filterList() } + + filterList() { + if(this.roomName) { + this.filterRoomList = this.rooms.filter(e => e.roomName.toLocaleLowerCase().indexOf(this.roomName.toLocaleLowerCase()) >= 0) + } else { + this.filterRoomList = this.rooms + } + } + ngOnInit() { // this.subscription = this.roomListSubject.pipe( // switchMap(roomList => @@ -145,7 +158,6 @@ export class ChatPage implements OnInit { this.roomLocalDataSourceService.getItemsLive().pipe( map((roomList) => roomList.map((room)=> new RoomViewModel(room))), tap((roomList) => { - console.log('update') this.updatemessage(roomList) }) ).subscribe() @@ -434,6 +446,7 @@ export class ChatPage implements OnInit { doRefresh(event) { setTimeout(() => { try { + this.ChatServiceService.getRoomList() event?.target?.complete(); } catch (error) { } }, 1000); diff --git a/src/app/ui/chat/component/edit-group/edit-group.page.ts b/src/app/ui/chat/component/edit-group/edit-group.page.ts index d36e8fb92..349afb53d 100644 --- a/src/app/ui/chat/component/edit-group/edit-group.page.ts +++ b/src/app/ui/chat/component/edit-group/edit-group.page.ts @@ -37,9 +37,7 @@ export class EditGroupPage implements OnInit { private httpErrorHandle: HttpErrorHandle, private toastService: ToastService, private chatServiceService: ChatServiceService, - ) { - this.loggedUser = SessionStore.user.ChatData['data']; - } + ) {} ngOnInit() { // this.chatService.refreshtoken(); diff --git a/src/app/ui/chat/component/group-contacts/group-contacts.page.html b/src/app/ui/chat/component/group-contacts/group-contacts.page.html index 41ea43bed..4ab9178a9 100644 --- a/src/app/ui/chat/component/group-contacts/group-contacts.page.html +++ b/src/app/ui/chat/component/group-contacts/group-contacts.page.html @@ -38,7 +38,7 @@
Contactos selecção: -
+

{{user.wxFullName }}

diff --git a/src/app/ui/chat/component/group-contacts/group-contacts.page.ts b/src/app/ui/chat/component/group-contacts/group-contacts.page.ts index b5322213d..8810af88e 100644 --- a/src/app/ui/chat/component/group-contacts/group-contacts.page.ts +++ b/src/app/ui/chat/component/group-contacts/group-contacts.page.ts @@ -189,40 +189,38 @@ export class GroupContactsPage implements OnInit { async deleteMember(user: UserContacts) { - this.showLoader = true; - // this.chatServiceService.removeMember({ - // roomId: this.roomId, - // members: [ user.wxUserId] - // }) + // if(this.currentMembers.length >= 3) { + this.showLoader = true; - // this.currentMembers = this.currentMembers.filter( e => e.wxUserId != user.wxUserId) + const result = await this.chatServiceService.removeMemberToRoom({ + id: this.roomId, + members: [ user.wxUserId] + }) - const result = await this.chatServiceService.removeMemberToRoom({ - id: this.roomId, - members: [ user.wxUserId] - }) + if(result.isOk()) { + this.currentMembers = this.currentMembers.filter( e => e.wxUserId != user.wxUserId) - if(result.isOk()) { - this.currentMembers = this.currentMembers.filter( e => e.wxUserId != user.wxUserId) + const firstLetter = user.wxFullName.charAt(0) - const firstLetter = user.wxFullName.charAt(0) + if(!this.userContainer[firstLetter]) { + user['isChecked'] = false + this.userContainer[firstLetter] = [user as any] + } else { + user['isChecked'] = false + this.userContainer[firstLetter].push(user as any) + } - if(!this.userContainer[firstLetter]) { - user['isChecked'] = false - this.userContainer[firstLetter] = [user as any] - } else { - user['isChecked'] = false - this.userContainer[firstLetter].push(user as any) + } else if(result.error instanceof HttpRequest) { + this.httpErrorHandle.httpStatusHandle(result.error) + } else if(result.error instanceof ZodError) { + console.log(result.error.issues) } - } else if(result.error instanceof HttpRequest) { - this.httpErrorHandle.httpStatusHandle(result.error) - } else if(result.error instanceof ZodError) { - console.log(result.error.issues) - } - - this.showLoader = false; + this.showLoader = false; + //} else { + // alert('---') + //} } diff --git a/src/app/ui/chat/component/messages/messages.page.html b/src/app/ui/chat/component/messages/messages.page.html index f5d844461..56dbac4c3 100644 --- a/src/app/ui/chat/component/messages/messages.page.html +++ b/src/app/ui/chat/component/messages/messages.page.html @@ -7,7 +7,7 @@
-
+
+
+ + {{ message.sender.wxFullName }} + +
@@ -115,7 +120,7 @@ - {{ attachment?.fileName || attachment?.description }} + {{ attachment?.fileName || attachment?.description }}
@@ -125,8 +130,8 @@
- - + +
diff --git a/src/app/ui/chat/component/messages/messages.page.ts b/src/app/ui/chat/component/messages/messages.page.ts index 1f44c0123..f93650169 100644 --- a/src/app/ui/chat/component/messages/messages.page.ts +++ b/src/app/ui/chat/component/messages/messages.page.ts @@ -300,7 +300,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy return 'allViewed' } else if(this.allReceived(message)) { return 'allReceived' - } else if (message.messageStatus == 'send') { + } else if (message.messageHasId) { return 'enviado' } else { return 'enviar' diff --git a/src/app/ui/chat/component/new-group/new-group.page.ts b/src/app/ui/chat/component/new-group/new-group.page.ts index 0b89437e5..a6455dfb3 100644 --- a/src/app/ui/chat/component/new-group/new-group.page.ts +++ b/src/app/ui/chat/component/new-group/new-group.page.ts @@ -31,7 +31,6 @@ export class NewGroupPage implements OnInit{ event: any link = '' documents: any; - loggedUserChat: any; contact: { Email: string DisplayName: string @@ -58,7 +57,6 @@ export class NewGroupPage implements OnInit{ private toastService: ToastService, ) { - this.loggedUserChat = SessionStore.user.ChatData['data']; this.isGroupCreated = false; } diff --git a/src/app/ui/chat/modal/chat-popover/chat-popover.page.html b/src/app/ui/chat/modal/chat-popover/chat-popover.page.html index ea6af89a8..42a3aa3b5 100644 --- a/src/app/ui/chat/modal/chat-popover/chat-popover.page.html +++ b/src/app/ui/chat/modal/chat-popover/chat-popover.page.html @@ -24,7 +24,7 @@ - +
diff --git a/src/app/ui/chat/modal/chat-popover/chat-popover.page.ts b/src/app/ui/chat/modal/chat-popover/chat-popover.page.ts index f3d5ecff8..ffa2591d2 100644 --- a/src/app/ui/chat/modal/chat-popover/chat-popover.page.ts +++ b/src/app/ui/chat/modal/chat-popover/chat-popover.page.ts @@ -1,16 +1,22 @@ import { Component, OnInit } from '@angular/core'; import { ModalController, NavParams, PopoverController } from '@ionic/angular'; import { ToastService } from 'src/app/services/toast.service'; -import { ThemeService } from 'src/app/services/theme.service' +import { ThemeService } from 'src/app/services/theme.service'; import { SetRoomOwnerPage } from 'src/app/ui/chat/modal/set-room-owner/set-room-owner.page'; import { SessionStore } from 'src/app/store/session.service'; import { ZodError } from 'zod'; - +import { MemberListLocalRepository } from 'src/app/module/chat/data/repository/member/member-list-local-repository.service'; import { ChatServiceService } from 'src/app/module/chat/domain/chat-service.service' import { RoomInfoPage } from '../room-info/room-info.page'; import { RoomType } from 'src/app/core/chat/entity/group'; import { isHttpResponse } from 'src/app/infra/http/http.service'; + + +interface ISetRoomOwner { + addAdminBeforeLeave?: null | boolean +} + @Component({ selector: 'app-chat-popover', templateUrl: './chat-popover.page.html', @@ -31,7 +37,8 @@ export class ChatPopoverPage implements OnInit { private navParams: NavParams, private toastService: ToastService, public ThemeService: ThemeService, - private ChatServiceService: ChatServiceService + private ChatServiceService: ChatServiceService, + private MemberListLocalRepository: MemberListLocalRepository ) { this.roomId = this.navParams.get('roomId'); this.isAdmin = this.navParams.get('isAdmin'); @@ -55,7 +62,7 @@ export class ChatPopoverPage implements OnInit { //Top menu options //Close - async setRoomOwner() { + async setRoomOwner({addAdminBeforeLeave = null}: ISetRoomOwner) { let classs; if (window.innerWidth < 701) { classs = 'modal modal-desktop' @@ -68,26 +75,36 @@ export class ChatPopoverPage implements OnInit { backdropDismiss: true, componentProps: { roomId: this.roomId, - isAdmin: this.isAdmin + isAdmin: this.isAdmin, + addAdminBeforeLeave } }); await modal.present(); - modal.onDidDismiss().then((res)=>{ + modal.onDidDismiss().then((res) => { if(res.data == 'success'){ this.leaveGroup(); //this.ChatSystemService.hidingRoom(this.roomId); } }); - } + } - setAdmin() { - this.setRoomOwner(); + setAdmin(data:ISetRoomOwner) { + this.setRoomOwner(data); } async leaveGroup() { - //this.setRoomOwner(); + if(this.isAdmin) { + const currentMemberToMap = await this.MemberListLocalRepository.getRoomMemberById(this.roomId) + const adminCount = currentMemberToMap.filter(e => e.isAdmin); + this.toastService._badRequest("É necessário adicionar um administrador"); + if(adminCount.length <= 1) { + this.setAdmin({addAdminBeforeLeave: true}); + return; + } + } + this.showLoader = true const result = await this.ChatServiceService.leaveRoom({ id: this.roomId, diff --git a/src/app/ui/chat/modal/group-contacts/group-contacts.page.html b/src/app/ui/chat/modal/group-contacts/group-contacts.page.html index ec158da9b..05366ab68 100644 --- a/src/app/ui/chat/modal/group-contacts/group-contacts.page.html +++ b/src/app/ui/chat/modal/group-contacts/group-contacts.page.html @@ -34,7 +34,7 @@
Contactos selecção:
- +

{{user.name}}

diff --git a/src/app/ui/chat/modal/messages/contacts/contacts.page.ts b/src/app/ui/chat/modal/messages/contacts/contacts.page.ts index 44f727f3a..1f7bcb179 100644 --- a/src/app/ui/chat/modal/messages/contacts/contacts.page.ts +++ b/src/app/ui/chat/modal/messages/contacts/contacts.page.ts @@ -18,7 +18,6 @@ import { RoomViewModel } from '../../../store/model/room'; }) export class ContactsPage implements OnInit { loading: boolean; - loggedUser: any; users = []; contacts:any; @@ -44,7 +43,6 @@ export class ContactsPage implements OnInit { private chatServiceService: ChatServiceService ) { - this.loggedUser = SessionStore.user.ChatData['data']; this.textSearch=""; this.dm=null; diff --git a/src/app/ui/chat/modal/messages/messages.page.html b/src/app/ui/chat/modal/messages/messages.page.html index d5278c622..513ce1627 100644 --- a/src/app/ui/chat/modal/messages/messages.page.html +++ b/src/app/ui/chat/modal/messages/messages.page.html @@ -68,6 +68,11 @@
+
+ + {{ message.sender.wxFullName }} + +
@@ -132,7 +137,7 @@ - {{ attachment?.fileName || attachment?.description }} + {{ attachment?.fileName || attachment?.description }}
@@ -142,8 +147,8 @@
- - + +
diff --git a/src/app/ui/chat/modal/messages/messages.page.ts b/src/app/ui/chat/modal/messages/messages.page.ts index 5bc8b9d9a..0fc749fbe 100644 --- a/src/app/ui/chat/modal/messages/messages.page.ts +++ b/src/app/ui/chat/modal/messages/messages.page.ts @@ -149,7 +149,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { return 'allViewed' } else if(this.allReceived(message)) { return 'allReceived' - } else if (message.messageStatus == 'send') { + } else if (message.messageHasId) { return 'enviado' } else { return 'enviar' diff --git a/src/app/ui/chat/modal/new-group/new-group.page.ts b/src/app/ui/chat/modal/new-group/new-group.page.ts index 70b01f1cb..24067b022 100644 --- a/src/app/ui/chat/modal/new-group/new-group.page.ts +++ b/src/app/ui/chat/modal/new-group/new-group.page.ts @@ -32,7 +32,6 @@ export class NewGroupPage implements OnInit { thedate: any; groupName: string; documents: any; - loggedUserChat: any; constructor( private pickerController: PickerController, @@ -43,7 +42,7 @@ export class NewGroupPage implements OnInit { public chatSystemService: ChatServiceService, private toastService: ToastService, ) { - this.loggedUserChat = SessionStore.user.ChatData['data']; + this.isGroupCreated = false; this.groupName = this.navParams.get('name'); this.documents = this.navParams.get('documents'); diff --git a/src/app/ui/chat/modal/set-room-owner/set-room-owner.page.ts b/src/app/ui/chat/modal/set-room-owner/set-room-owner.page.ts index bf70e4708..944759163 100644 --- a/src/app/ui/chat/modal/set-room-owner/set-room-owner.page.ts +++ b/src/app/ui/chat/modal/set-room-owner/set-room-owner.page.ts @@ -19,6 +19,7 @@ export class SetRoomOwnerPage implements OnInit { textSearch:string = ""; roomId:any; members:any; + addAdminBeforeLeave: boolean | null; roomMembers$!: DexieObservable constructor( @@ -31,6 +32,7 @@ export class SetRoomOwnerPage implements OnInit { ) { this.roomId = this.navParams.get('roomId'); this.members = this.navParams.get('members'); + this.addAdminBeforeLeave = this.navParams.get('addAdminBeforeLeave'); } ngOnInit() { @@ -68,8 +70,10 @@ export class SetRoomOwnerPage implements OnInit { }); if(result.isOk()) { - this.chatServiceService.getRoomById(this.roomId); - // this.modalController.dismiss('success'); + await this.chatServiceService.getRoomById(this.roomId); + if(this.addAdminBeforeLeave) { + this.modalController.dismiss('success'); + } } else { this.toastService._badRequest('Não foi possível completar a ação, por favor tente novamente.'); } diff --git a/src/app/ui/chat/store/model/message.ts b/src/app/ui/chat/store/model/message.ts index f2d00ce06..47f898815 100644 --- a/src/app/ui/chat/store/model/message.ts +++ b/src/app/ui/chat/store/model/message.ts @@ -99,9 +99,11 @@ export class MessageViewModal { } - get messageStatus() { + get messageHasId() { if(this.id) { - return 'send' + return true + } else { + return false } } diff --git a/src/app/ui/shared/components/header-pr/header-pr.page.ts b/src/app/ui/shared/components/header-pr/header-pr.page.ts index fbc7053cb..703e2796c 100644 --- a/src/app/ui/shared/components/header-pr/header-pr.page.ts +++ b/src/app/ui/shared/components/header-pr/header-pr.page.ts @@ -1,5 +1,5 @@ import { Component, OnInit } from '@angular/core'; -import { LoginUserRespose } from 'src/app/models/user.model'; +import { UserSession } from 'src/app/models/user.model'; import { AuthService } from 'src/app/services/auth.service'; import { SessionStore } from 'src/app/store/session.service'; @@ -10,7 +10,7 @@ import { SessionStore } from 'src/app/store/session.service'; }) export class HeaderPrPage implements OnInit { - loggeduser: LoginUserRespose; + loggeduser: UserSession; constructor(authService: AuthService) { this.loggeduser = SessionStore.user; diff --git a/src/app/ui/shared/components/header/header.page.html b/src/app/ui/shared/components/header/header.page.html index 78dfb8c18..fe888b2a4 100644 --- a/src/app/ui/shared/components/header/header.page.html +++ b/src/app/ui/shared/components/header/header.page.html @@ -113,8 +113,11 @@
+ +
+ *ngIf="p.userPermissionCount([permissionList.Agenda.access, permissionList.Gabinete.access, permissionList.Actions.access, permissionList.Chat.access]) >= 2 || (p.userPermission([permissionList.Agenda.access])) || p.userPermission([permissionList.Gabinete.access])">
= []; @@ -134,7 +134,7 @@ export class HeaderPage implements OnInit { async getProfilpicture(tracing?: TracingType) { if (this.SessionStore.user.UserPhoto) { - + const base = await this.UserRepositoryService.getUserProfilePhoto(this.SessionStore.user.UserPhoto, tracing) if(base.isOk()) { diff --git a/src/environments/suport/dev.ts b/src/environments/suport/dev.ts index ff5a355cc..2ecb4ef5b 100644 --- a/src/environments/suport/dev.ts +++ b/src/environments/suport/dev.ts @@ -1,51 +1,51 @@ import { versionData } from '../../../version/git-version' import { Environment } from './../../app/models/envarioment' -export const environment: Environment = { - id:'3', - apiURL: 'http://gpr-dev-01:83/jwt/api/', - /* apiURL: 'https://gdapi-dev-0.dyndns.info/jwt/api/', */ - apiChatUrl: 'https://gdchat-dev.dyndns.info/api/v1/', - apiWsChatUrl: 'wss://gdchat-dev.dyndns.info/websocket', - apiPCURL: 'http://gpr-dev-01:86/api/', - /* apiPCURL: 'https://gdcmapi-dev.dyndns.info/api/', */ - logoLabel: 'Presidente da República', - despachoLabel: 'Presidenciais', - despachoLabel2: 'Despachos Presidênciais', - production: false, - domain: 'gabinetedigital.local', - defaultuser: 'paulo.pinto@gabinetedigital.local', - defaultuserpwd: 'tabteste@006', - chatOffline: true, - presidential: true, - version: versionData, - agendaPR: 'Agenda do PR', - agendaVP: 'Agenda do MD', - PR: 'PR', - VP: '', - dispatchPR: 'Despachos Presidênciais', - sentryUrl: 'https://9920cc36f1d740b987426ee8d80cf588@o4504340905525248.ingest.sentry.io/4504340946419712', - storageProduction: true, - rejectUnauthorized: "true", - fileHub: 'https://gdcmapi-dev.dyndns.info/FileHub' -/* production: true, - domain: 'gabinetedigital.local', - defaultuser: '', - defaultuserpwd: '', - chatOffline: true, - presidential: false, - version: versionData, - sentryUrl: 'https://9920cc36f1d740b987426ee8d80cf588@o4504340905525248.ingest.sentry.io/4504340946419712', - logoLabel: 'doneIT', - despachoLabel: 'do Titular', - despachoLabel2: 'Despachos do Titular', - agendaPR: 'Agenda do Titular', - agendaVP: 'Agenda do (MD)', - PR: 'Titular', - VP: '', - dispatchPR: 'Despachos Titular', - storageProduction: true */ -}; +// export const environment: Environment = { +// id:'3', +// apiURL: 'http://gpr-dev-01:83/jwt/api/', +// /* apiURL: 'https://gdapi-dev-0.dyndns.info/jwt/api/', */ +// apiChatUrl: 'https://gdchat-dev.dyndns.info/api/v1/', +// apiWsChatUrl: 'wss://gdchat-dev.dyndns.info/websocket', +// apiPCURL: 'http://gpr-dev-01:86/api/', +// /* apiPCURL: 'https://gdcmapi-dev.dyndns.info/api/', */ +// logoLabel: 'Presidente da República', +// despachoLabel: 'Presidenciais', +// despachoLabel2: 'Despachos Presidênciais', +// production: false, +// domain: 'gabinetedigital.local', +// defaultuser: 'paulo.pinto@gabinetedigital.local', +// defaultuserpwd: 'tabteste@006', +// chatOffline: true, +// presidential: true, +// version: versionData, +// agendaPR: 'Agenda do PR', +// agendaVP: 'Agenda do MD', +// PR: 'PR', +// VP: '', +// dispatchPR: 'Despachos Presidênciais', +// sentryUrl: 'https://9920cc36f1d740b987426ee8d80cf588@o4504340905525248.ingest.sentry.io/4504340946419712', +// storageProduction: true, +// rejectUnauthorized: "true", +// fileHub: 'https://gdcmapi-dev.dyndns.info/FileHub' +// /* production: true, +// domain: 'gabinetedigital.local', +// defaultuser: '', +// defaultuserpwd: '', +// chatOffline: true, +// presidential: false, +// version: versionData, +// sentryUrl: 'https://9920cc36f1d740b987426ee8d80cf588@o4504340905525248.ingest.sentry.io/4504340946419712', +// logoLabel: 'doneIT', +// despachoLabel: 'do Titular', +// despachoLabel2: 'Despachos do Titular', +// agendaPR: 'Agenda do Titular', +// agendaVP: 'Agenda do (MD)', +// PR: 'Titular', +// VP: '', +// dispatchPR: 'Despachos Titular', +// storageProduction: true */ +// }; export const DevDev: Environment = { diff --git a/version/git-version.ts b/version/git-version.ts index e2fabd041..eafe497b1 100644 --- a/version/git-version.ts +++ b/version/git-version.ts @@ -1,11 +1,11 @@ export let versionData = { - "shortSHA": "eedb66a1c", - "SHA": "eedb66a1cf766552965265cc0b4d5c30ed7ed57b", - "branch": "developer", - "lastCommitAuthor": "'Peter Maquiran'", - "lastCommitTime": "'Tue Oct 29 16:00:19 2024 +0100'", - "lastCommitMessage": "add telemetry", - "lastCommitNumber": "6122", - "changeStatus": "On branch developer\nYour branch is ahead of 'origin/developer' by 1 commit.\n (use \"git push\" to publish your local commits)\n\nChanges to be committed:\n (use \"git restore --staged ...\" to unstage)\n\tmodified: src/app/pages/events/attendees/attendees.page.ts\n\tmodified: src/app/shared/event/attendee-modal/attendee-modal.page.ts", + "shortSHA": "470b1e7f0", + "SHA": "470b1e7f0e0e7a4ae7155d7b88c322e770e21f26", + "branch": "feature/login-v2", + "lastCommitAuthor": "'peter.maquiran'", + "lastCommitTime": "'Tue Jun 3 09:42:08 2025 +0100'", + "lastCommitMessage": "fix", + "lastCommitNumber": "6141", + "changeStatus": "On branch feature/login-v2\nYour branch is ahead of 'origin/feature/login-v2' by 6 commits.\n (use \"git push\" to publish your local commits)\n\nChanges to be committed:\n (use \"git restore --staged ...\" to unstage)\n\tmodified: version/git-version.ts", "changeAuthor": "peter.maquiran" } \ No newline at end of file