mobile create grupo and contact

This commit is contained in:
Peter Maquiran
2024-09-19 09:16:14 +01:00
parent 9e7a8b6cb6
commit 1f08eb5514
6 changed files with 199 additions and 310 deletions
@@ -47,7 +47,7 @@
</div>
</div>
<div *ngFor="let userContainer of userContainer | keyvalue;" >
<div class="item-divider">
@@ -55,9 +55,9 @@
</div>
<div *ngFor="let user of userContainer.value" class="d-flex px-20 align-center">
<ion-checkbox [(ngModel)]="user.isChecked" color="primary" (click)="selectedContact(user)"></ion-checkbox>
<ion-label class="flex-grow-1 px-10">{{user.name}}</ion-label>
<div class="icon"><ion-icon class="{{user.status}}" name="ellipse"></ion-icon></div>
<ion-checkbox [(ngModel)]="user.isChecked" color="primary" (ionChange)="onChangeCheckBox(user)"></ion-checkbox>
<ion-label class="flex-grow-1 px-10">{{user.wxFullName}}</ion-label>
<!-- <div class="icon"><ion-icon class="{{user.status}}" name="ellipse"></ion-icon></div> -->
</div>
</div>
@@ -1,4 +1,4 @@
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { ModalController, NavParams } from '@ionic/angular';
import * as _ from 'lodash';
@@ -6,7 +6,14 @@ import { AuthService } from 'src/app/services/auth.service';
import { GroupMessagesPage } from '../group-messages.page';
import { ThemeService } from 'src/app/services/theme.service'
import { SessionStore } from 'src/app/store/session.service';
// import { ChatSystemService } from 'src/app/services/chat/chat-system.service';
import { HttpErrorHandle } from 'src/app/services/http-error-handle.service';
import { ContactRepositoryService } from 'src/app/services/Repositorys/contacts/repository/contacts-repository.service';
import { MemberListLocalRepository } from 'src/app/module/chat/data/repository/member/member-list-local-repository.service'
import { UserContacts } from 'src/app/services/Repositorys/contacts/data-source/contacts-data-source.service';
import { ToastService } from 'src/app/services/toast.service';
import { ChatServiceService } from 'src/app/module/chat/domain/chat-service.service';
import { ZodError } from 'zod';
@Component({
selector: 'app-group-contacts',
@@ -35,11 +42,23 @@ export class GroupContactsPage implements OnInit {
objectUserSingleStone = []
userContainer = {}
roomId:string;
allChatUsers: UserContacts[] = [];
currentMembers:UserContacts[];
selectedUsers: number[] =[]
get hasMemberToUpload() {
return this.selectedUsers.length >= 1
}
constructor(
private modalController: ModalController,
public ThemeService: ThemeService,
// public ChatSystemService: ChatSystemService,
public chatServiceService: ChatServiceService,
private navParams: NavParams,
private httpErrorHandle: HttpErrorHandle,
private contactsRepositoryService: ContactRepositoryService,
private MemberListLocalRepository: MemberListLocalRepository,
private toastService: ToastService,
)
{
@@ -48,7 +67,7 @@ export class GroupContactsPage implements OnInit {
// this.room=null;
// this.isGroupCreated = this.navParams.get('isCreated');
// this.groupName = this.navParams.get('name');
// this.room = this.navParams.get('room');
this.room = this.navParams.get('roomId');
// this.members = this.navParams.get('members');
}
@@ -60,60 +79,99 @@ export class GroupContactsPage implements OnInit {
}
loadUsers(){
// this.options = {
// headers: this.headers,
// };
// this.chatService.getAllUsers().subscribe((res:any)=>{
// if(this.members) {
// this.contacts = res.users.filter(f => !this.members.some(item => item._id === f._id));
// }
// else{
// this.contacts = res.users.filter(data => data.username != this.sessionStore.user.UserName);
// }
// this.users = this.contacts.sort((a,b) => {
// if(a.name < b.name){
// return -1;
// }
// if(a.name > b.name){
// return 1;
// }
// return 0;
// });
async loadUsers() {
const getallChatUsers = await this.contactsRepositoryService.getUsers()
const getRoomById = await this.chatServiceService.getRoomById(this.roomId)
console.log({getallChatUsers, getRoomById})
if(getallChatUsers.isOk() && getRoomById.isOk()) {
this.allChatUsers = getallChatUsers.value.data.result.sort((a,b) => {
if(a.wxFullName < b.wxFullName) {
return -1;
}
if(a.wxFullName > b.wxFullName) {
return 1;
}
return 0;
});
const currentMemberToMap = await this.MemberListLocalRepository.getRoomMemberById(this.roomId)
console.log({currentMemberToMap})
this.currentMembers = currentMemberToMap.map((e)=> ({
userPhoto: e.userPhoto,
wxeMail: e.wxeMail,
wxFullName: e.wxFullName,
wxUserId: e.wxUserId
}))
const currentMemberIds = this.currentMembers.map(e => e.wxUserId)
const allSelectableUsers = this.allChatUsers.filter(e => !currentMemberIds.includes(e.wxUserId))
for(const user of allSelectableUsers) {
const firstLetter = user.wxFullName.charAt(0)
if(!this.userContainer[firstLetter]) {
user['isChecked'] = false
this.userContainer[firstLetter] = [user as any]
} else {
const userIds = this.userContainer[firstLetter].map( e => e.wxUserId)
if(!userIds.includes(user.wxUserId)) {
user['isChecked'] = false
this.userContainer[firstLetter].push(user as any)
}
}
}
// for( const user of this.users) {
// const foundUser = this.objectUserSingleStone.find( e => e.name == user.name)
// if(!foundUser) {
// this.objectUserSingleStone.push(user)
// } else {
// 'not found'
// }
// }
}
else if (getRoomById.isErr() && getRoomById.error instanceof HttpResponse) {
this.httpErrorHandle.httpStatusHandle(getRoomById.error)
} else if (getallChatUsers.isErr() && getallChatUsers.error instanceof HttpResponse) {
this.httpErrorHandle.httpStatusHandle(getallChatUsers.error)
} else if (getRoomById.isErr() ) {
console.log(getRoomById.error)
} else if (getallChatUsers.isErr() ) {
console.log(getallChatUsers.error)
} else {
this.toastService._badRequest("Pedimos desculpa mas não foi possível executar a acção. Por favor, contacte o apoio técnico.")
}
// const userContainer = {}
// for(const user of this.objectUserSingleStone) {
// const firstLetter = user.name.charAt(0)
// if(!userContainer[firstLetter]) {
// userContainer[firstLetter] = [user]
// } else {
// userContainer[firstLetter].push(user)
// }
// }
// this.userContainer = userContainer
this.showLoader = false;
}
// this.showLoader = false;
// });
async updateGroup() {
if(this.hasMemberToUpload) {
this.showLoader = true;
const addMembers = await this.chatServiceService.addMemberToRoom({
id: this.roomId,
members: this.selectedUsers
})
if(addMembers.isOk()) {
// this.addContacts(this.roomId);
//this.openGroupMessage.emit(this.roomId);
await this.chatServiceService.getRoomById(this.roomId);
this.modalController.dismiss({roomId: this.roomId})
} else if(addMembers.error instanceof HttpRequest) {
this.httpErrorHandle.httpStatusHandle(addMembers.error)
}
} else {
// this.openGroupMessage.emit(this.roomId);
console.log('nothoing to add')
}
this.showLoader = false;
}
getMembers(){
@@ -134,19 +192,6 @@ export class GroupContactsPage implements OnInit {
return null;
}
deleteMember(data:any){
let body = {
"roomId": this.room._id,
"userId": data._id,
}
if(this.room.t == "p"){
}
else if(this.room.t == "c"){
}
}
doRefresh(ev){
@@ -159,121 +204,83 @@ export class GroupContactsPage implements OnInit {
this.modalController.dismiss();
}
onChange(event) {
this.textSearch = event.detail.value;
const users = this.contacts.filter( e => e.name.toLowerCase().includes(this.textSearch.toLowerCase())).sort((a,b) => {
if(a.name < b.name) {
FilterUserListedByTextSearch() {
return this.allChatUsers.filter( e => e.wxFullName.toLowerCase().includes(this.textSearch.toLowerCase())).sort((a,b) => {
if(a.wxFullName < b.wxFullName) {
return -1;
}
if(a.name > b.name) {
if(a.wxFullName > b.wxFullName) {
return 1;
}
return 0;
});
}
const selectedUsers = this.users.filter( e => e?.isChecked == true)
users.forEach( (user, index) => {
if(user[index]) {
console.log({user, index})
const isCheck = selectedUsers.find( e => e._id == user._id)?.isChecked
if(isCheck) {
user[index].isChecked = isCheck
}
onChangeCheckBox(user: UserContacts & {isChecked: boolean}) {
console.log(user)
// if(user[index].isChecked) {
// console.log('user[index].isChecked', user[index].isChecked)
// }
if(user.isChecked) {
this.selectedUsers.push(user.wxUserId)
} else {
this.selectedUsers = this.selectedUsers.filter(e => e!= user.wxUserId)
}
}
onChange(event) {
this.textSearch = event.detail.value;
const filteredUserList: (UserContacts & {isChecked: boolean})[] = this.FilterUserListedByTextSearch() as any
const userContainer = {}
for(const user of filteredUserList) {
const firstLetter = user.wxFullName.charAt(0)
if(!userContainer[firstLetter]) {
user.isChecked = this.selectedUsers.includes(user.wxUserId)
userContainer[firstLetter] = [user]
} else {
user.isChecked = this.selectedUsers.includes(user.wxUserId)
userContainer[firstLetter].push(user)
}
}
this.userContainer = userContainer
}
async deleteMember(user: UserContacts) {
this.showLoader = true;
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)
const firstLetter = user.wxFullName.charAt(0)
let a = this.objectUserSingleStone.filter( e => e.name.toLowerCase().includes(this.textSearch.toLowerCase()))
let b = {}
for(const user of a) {
const firstLetter = user.name.charAt(0)
if(!b[firstLetter]) {
b[firstLetter] = [user]
if(!this.userContainer[firstLetter]) {
user['isChecked'] = false
this.userContainer[firstLetter] = [user as any]
} else {
b[firstLetter].push(user)
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)
}
this.userContainer = b
}
clicked(){
}
selectedContact(user:any) {
/* this.groupName = this.room.name; */
if(user.isChecked != true ) {
user.isChecked = false
} else {
user.isChecked = true
}
const userIndex = this.objectUserSingleStone.findIndex((e) => e._id == user._id)
this.objectUserSingleStone[userIndex].isChecked = user.isChecked
}
addContacts(room:any){
this.selectedUserList = this.users.filter(function(contact) {
return contact.isChecked == true;
});
this.selectedUserList.forEach(user=>{
let body ={
"roomId":room._id,
"userId":user._id,
}
});
}
loading = false
updateGroup(){
if(this.loading) {
return
}
this.loading = true
console.log('this.room', this.room)
this.showLoader = false;
}
async openGroupMessages(roomId:any){
const modal = await this.modalController.create({
component: GroupMessagesPage,
componentProps: {
roomId: roomId,
},
cssClass: 'group-messages',
backdropDismiss: false
});
modal.onDidDismiss().then(() => {
this.close();
});
await modal.present();
}
}
@@ -188,7 +188,7 @@
<ion-fab horizontal="start" vertical="bottom" slot="fixed">
<div *ngFor="let user of RoomStore.userTyping$; let i = index">
{{ user }} <ng-container *ngIf="i == userTyping$.length - 1">... </ng-container>
{{ user }} <ng-container *ngIf="i == RoomStore.userTyping$.length - 1">... </ng-container>
</div>
</ion-fab>
@@ -74,7 +74,6 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
showMessageOptions = false;
selectedMsgId: string;
task: ExpedientTaskModalPageNavParamsTask;
LoadedDocument: any = null;
recording = false;
@@ -92,10 +91,6 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
@ViewChild('filechooser') fileChooserElementRef: ElementRef;
@ViewChild('array') myInputRef!: ElementRef;
//items: File[] = [];
fileSelected?: Blob;
pdfUrl?: string;
base64File: string;
downloadProgess: number;
downloadLoader: boolean;
@@ -103,10 +98,6 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
sessionStore = SessionStore
SessionStore = SessionStore
//userTyping$: DexieObservable<TypingTable[] | undefined>
userTyping$: TypingTable[] | undefined
newMessagesStream!: Subscription
selectedMessage: any = null;
emojis: string[] = ['😊', '😂', '❤️', '👍', '😢']; // Add more emojis as needed
textField = ''
@@ -326,12 +317,9 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
this.deleteRecording();
}
load() {
this.getChatMembers();
}
doRefresh(ev: any) {
this.load();
ev.target.complete();
}
@@ -478,7 +466,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
await modal.present();
}
getChatMembers() {}
showDateDuration(start: any) {
let end;
+24 -130
View File
@@ -6,6 +6,10 @@ import { ThemeService } from 'src/app/services/theme.service';
import { SessionStore } from 'src/app/store/session.service';
import { ToastService } from 'src/app/services/toast.service';
import { catchError } from 'rxjs/operators';
import { ChatServiceService } from 'src/app/module/chat/domain/chat-service.service'
import { UDate } from 'src/app/utils/date';
import { HttpErrorResponse } from '@angular/common/http';
@Component({
selector: 'app-new-group',
@@ -29,7 +33,7 @@ export class NewGroupPage implements OnInit {
private modalController: ModalController,
private navParams: NavParams,
public ThemeService: ThemeService,
// public ChatSystemService: ChatSystemService,
public chatSystemService: ChatServiceService,
private toastService: ToastService,
) {
this.loggedUserChat = SessionStore.user.ChatData['data'];
@@ -38,10 +42,7 @@ export class NewGroupPage implements OnInit {
this.documents = this.navParams.get('documents');
}
ngOnInit() {
// this.chatService.refreshtoken();
// console.log(this.documents)
}
ngOnInit() {}
_ionChange(event) {
this.showDuration = event.detail.checked;
@@ -59,136 +60,29 @@ export class NewGroupPage implements OnInit {
async createGroup() {
// let name = this.groupName.split(' ').join('-');
// //Take out all special characters in string
// name = name.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
const result = await this.chatSystemService.createRoom({
roomName: this.groupName,
createdBy: SessionStore.user.UserId,
roomType: 0,
expirationDate: this.displayDuration?.toISOString() ? UDate.GetDateWithTimeZone(this.displayDuration) : null,
members: []
})
// let customFields = {}
// let res: any;
// if(!SessionStore.user?.ChatData?.data) {
// this.toastService._successMessage("Chat temporariamente indisponível")
// }
// try {
// if (this.thedate) {
// let customFields = {
// "countDownDate": this.thedate
// }
// res = await this.ChatSystemService.createPrivateRoom(name, SessionStore.user.UserName, customFields);
// }
// else {
// res = await this.ChatSystemService.createPrivateRoom(name, SessionStore.user.UserName, customFields);
// }
// try {
// this.isGroupCreated = true;
// this.addContacts(res.result);
// this.ChatSystemService.getRoom([res.result]);
// setTimeout(() => {
// this.ChatSystemService.subscribeToRoomUpdate(res.result.rid, res.result);
// }, 10)
// } catch (error) {
// await this.ChatSystemService.getUser();
// await this.ChatSystemService.getAllRooms();
// await this.ChatSystemService.subscribeToRoom();
// this.isGroupCreated = true;
// this.addContacts(res.result);
// this.ChatSystemService.getRoom([res.result]);
// setTimeout(() => {
// this.ChatSystemService.subscribeToRoomUpdate(res.result.rid, res.result);
// }, 10)
// }
// if (res?.result?.rid) {
// this.ChatSystemService.getAllRooms(() => {
// if (!this.ChatSystemService.getGroupRoom(res.result.rid)) {
// this.createGroupWithAttachmentsCath(res)
// } else {
// setTimeout(() => {
// this.createGroupWithAttachments(res)
// }, 500)
// }
// }, res.result.rid);
// } else {
// this.toastService._badRequest('Existe um grupo com este nome!');
// }
// } catch(error) {
// this.toastService._successMessage("Chat temporariamente indisponível")
// }
if(result.isOk()) {
await this.chatSystemService.getRoomById(result.value.id)
this.addContacts(result.value.id)
//this.addGroupMessage.emit(result.value.id);
} else if(result.error instanceof HttpErrorResponse) {
// this.httpErrorHandle.httpStatusHandle(result.error)
} else {
this.toastService._badRequest('Por favor, contacta um administrador.');
}
}
createGroupWithAttachmentsCath(res: any) {
// if (!this.ChatSystemService.getGroupRoom(res.result.rid)) {
// setTimeout(() => {
// this.createGroupWithAttachmentsCath(res)
// }, 1500)
// } else {
// this.createGroupWithAttachments(res)
// }
}
createGroupWithAttachments(res: any) {
// this.ChatSystemService.getGroupRoom(res.result.rid).hasLoadHistory = true;
// if (this.documents) {
// this.documents.forEach(element => {
// this.ChatSystemService.getGroupRoom(res.result.rid).send({
// file: {
// "name": element.Assunto,
// "type": "application/webtrix",
// "ApplicationId": element.ApplicationId,
// "DocId": element.DocId,
// "Assunto": element.Assunto,
// },
// temporaryData: {
// data: {
// selected: {
// Id: element.DocId,
// ApplicationType: element.ApplicationId
// }
// }
// },
// attachments: [{
// "title": element.Assunto,
// "description": element.Assunto,
// "title_link_download": true,
// "type": "webtrix",
// "text": element.Assunto,
// "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png",
// }],
// })
// });
// }
// this.ChatSystemService.getAllRooms();
// setTimeout(() => {
// this.groupName = ""
// }, 150);
}
async addContacts(room) {
async addContacts(roomId) {
this.close();
let name = this.groupName.split(' ').join('-');
@@ -197,7 +91,7 @@ export class NewGroupPage implements OnInit {
const modal = await this.modalController.create({
component: GroupContactsPage,
componentProps: {
room: room,
roomId: roomId,
},
cssClass: 'contacts',
backdropDismiss: false