Skip to content

Commit

Permalink
update message seen functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
skyfox93 committed Apr 18, 2024
1 parent c7a10a6 commit 88324b9
Show file tree
Hide file tree
Showing 10 changed files with 110 additions and 31 deletions.
46 changes: 46 additions & 0 deletions client/src/FetchActions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { APP_API_BASE_URL } from './configs';
import { Message } from './types';

export const getRequest = (
url: string,
Expand Down Expand Up @@ -26,6 +27,42 @@ export const getRequest = (
}
});
};

export const patchRequest = (
url: string,
body: any,
onSuccess: Function,
abortController?: AbortController,
onError = (statusCode?: Number, statusText?: string) => {},
) => {
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
signal: abortController?.signal,
body: JSON.stringify(body),
};
fetch(url, options)
.then((resp) => {
if (!resp.ok) {
onError(resp.status, resp.statusText);
} else {
return resp.json();
}
})
.then((data) => onSuccess(data))
.catch((e) => {
if (e.name === 'AbortError') {
// usually, this abort is intentional due to a change in props
console.log('fetch aborted');
} else {
onError();
}
});
};
// best practice for fetching is to allow fetches to be aborted, in case props change while a fetch is in progress

export const fetchNeeds = (
limit: string,
offset: string,
Expand Down Expand Up @@ -63,3 +100,12 @@ export const fetchInbox = (
const assetsApiRequest = new URL(`${APP_API_BASE_URL}/transactions/inbox`);
getRequest(assetsApiRequest.href + assetsApiRequest.hash, onSuccess, abortController, onError);
};

export const updateMessage = (
messageBody: Message,
onSuccess: Function,
onError = (statusCode?: Number, statusText?: string) => {},
) => {
const messageApiRequest = new URL(`${APP_API_BASE_URL}/messages/${messageBody.id}`);
patchRequest(messageApiRequest.href, messageBody, onSuccess, new AbortController(), () => {});
};
5 changes: 4 additions & 1 deletion client/src/components/Users/Inbox/MessageCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { makeStyles } from 'tss-react/mui';
import type { Theme } from '@mui/material/styles';

import { Typography } from '@mui/material';
import { Button } from '@mui/base';

const useStyles = makeStyles()((theme: Theme) => ({
currentUserMessage: {
Expand All @@ -30,14 +31,15 @@ function MessageCard({
senderName,
isCurrentUser,
dateString,
messageReadCallback,
}: {
senderName: string;
text: string;
isCurrentUser: boolean;
dateString: string;
messageReadCallback: React.MouseEventHandler<HTMLButtonElement>;
}): JSX.Element {
const { classes } = useStyles();

return (
<div className={isCurrentUser ? classes.currentUserMessage : classes.otherUserMessage}>
<Typography variant="subtitle2" color="text.primary">
Expand All @@ -46,6 +48,7 @@ function MessageCard({
<Typography variant="body2" color="text.primary">
{dateString}
</Typography>
<Button onClick={messageReadCallback}> Read </Button>
</div>
);
}
Expand Down
1 change: 1 addition & 0 deletions client/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ export type Message = {
sendingUserId: number | null;
sendingOrgId: number | null;
created_date: string;
read: boolean;
};

export type Option = {
Expand Down
49 changes: 29 additions & 20 deletions client/src/views/Messages.tsx
Original file line number Diff line number Diff line change
@@ -1,38 +1,47 @@
import React from 'react';
import { Message } from '../types';
import { Message, Transaction } from '../types';
import MessageCard from '../components/Users/Inbox/MessageCard';
import { patchRequest, updateMessage } from '../FetchActions';

Check warning on line 4 in client/src/views/Messages.tsx

View workflow job for this annotation

GitHub Actions / linting

'patchRequest' is defined but never used

Check failure on line 4 in client/src/views/Messages.tsx

View workflow job for this annotation

GitHub Actions / linting

'patchRequest' is defined but never used

function Messages({ messages, transaction, user }: any) {
const formatDate = (date: string): string => {
return new Date(date).toLocaleString('en-US');
};

const getSenderName = (transaction: Transaction, message: Message) => {
if (message.sendingOrgId) {
if (message.sendingOrgId === transaction.claimer?.id) {
return transaction.claimer.name;
} else if (message.sendingOrgId === transaction.donater_organization?.id) {
return transaction.donater_organization.name;
} else {
return '';
}
} else if (message.sendingUserId === (user && user.id)) {
return user.firstName;
} else {
return transaction.donater_user?.firstName;
}
};

return (
<div className="message-list">
{messages.map((message: Message) => {
const sendingOrg = [transaction.donater_organization, transaction.claimer].find(
(org) => org && org.id === message.sendingOrgId,
);
const userOrg =
user &&
user.organizations[0] &&
user.organizations[0].organization &&
user.organizations[0].organization.id;

let sendingUser = null;
if (transaction.donater_user && transaction.donater_user.id === message.sendingUserId) {
sendingUser = transaction.donater_user;
}
const senderName = sendingOrg ? sendingOrg.name : sendingUser && sendingUser.firstName;
const isCurrentUser =
message.sendingUserId === user.id || (userOrg && userOrg === message.sendingOrgId);

const markMessageRead: React.MouseEventHandler<HTMLButtonElement> = (event) =>
updateMessage(
message,
() => {},
() => {
console.log('error');
},
);
return (
<MessageCard
senderName={senderName}
messageReadCallback={markMessageRead}
senderName={getSenderName(transaction, message)}
text={message.text}
dateString={formatDate(message.created_date)}
isCurrentUser={isCurrentUser}
isCurrentUser={message.sendingUserId === (user && user.id)}
/>
);
})}
Expand Down
5 changes: 4 additions & 1 deletion server/src/messages/dto/create-message.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@ export class CreateMessageDto {
@IsNotEmpty()
text: string;

@IsOptional()
read: boolean

@IsNotEmpty()
transaction: Transaction;

@IsNotEmpty()
sending_user: User;

@IsOptional()
sending_org: Organization;
sending_org?: Organization;
}
20 changes: 18 additions & 2 deletions server/src/messages/dto/return-message.dto.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
import { IsNotEmpty } from 'class-validator';
import { IsNotEmpty, IsOptional } from 'class-validator';

import { CreateMessageDto } from './create-message.dto';
import { Transaction } from 'src/transactions/entities/transaction.entity';
import { User } from 'src/acccount-manager/entities/user.entity';
import { Organization } from 'src/organizations/entities/organization.entity';

export class ReturnMessageDto extends CreateMessageDto {
id: number

text: string

read: boolean

@IsNotEmpty()
id: number;
transaction: Transaction;

@IsOptional()
sending_user: User;

@IsOptional()
sending_org?: Organization;

}
2 changes: 1 addition & 1 deletion server/src/messages/dto/update-message.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ import { PickType } from '@nestjs/swagger';

import { CreateMessageDto } from './create-message.dto';

export class UpdateMessageDto extends PickType(CreateMessageDto, ['text'] as const) {}
export class UpdateMessageDto extends PickType(CreateMessageDto, ['text', 'read' ] as const) {}
5 changes: 3 additions & 2 deletions server/src/messages/entities/message.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,11 @@ export class Message {
@Column({ nullable: true })
sendingOrgId: number;

@Column()
read: boolean

@ManyToOne(() => Transaction, (transaction) => transaction.messages)
@JoinColumn()
transaction: Transaction;

@OneToMany(() => Receivedmessage, (userMessage) => userMessage.message)
readReceipts?: Receivedmessage[];
}
6 changes: 3 additions & 3 deletions server/src/messages/messages.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class MessagesController {
async create(
@Request() request: ExpressRequest,
@Body() createMessageDto: CreateMessageDto,
): Promise<Message> {
): Promise<ReturnMessageDto> {
const newMessage = await this.messagesService.create(createMessageDto);
return newMessage;
}
Expand All @@ -52,10 +52,10 @@ export class MessagesController {
@Patch(':id')
@ApiOperation({ summary: 'Update a message.' })
async update(
@Param('id') id: string,
@Param('id') id: number,
@Body() updateMessageDto: UpdateMessageDto,
): Promise<ReturnMessageDto> {
return this.messagesService.update(+id, updateMessageDto);
return this.messagesService.update(id, updateMessageDto);
}

@Delete(':id')
Expand Down
2 changes: 1 addition & 1 deletion server/src/transactions/transactions.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Get, Post, Body, Query, Param, Patch, Delete, Controller } from '@nestjs/common';
import { Get, Post, Body, Query, Param, Patch, Delete, Controller, UseGuards } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';

import { TransactionsService } from './transactions.service';
Expand Down

0 comments on commit 88324b9

Please sign in to comment.