Skip to content

Commit

Permalink
Merge pull request #101 from cuappdev/notifs
Browse files Browse the repository at this point in the history
Adding all notifications
  • Loading branch information
ashleynhs authored Dec 2, 2024
2 parents 925fb59 + 5b17b86 commit 0265073
Show file tree
Hide file tree
Showing 5 changed files with 166 additions and 3 deletions.
12 changes: 11 additions & 1 deletion src/api/controllers/NotifController.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Body, CurrentUser, Delete, Get, JsonController, Params, Post } from 'routing-controllers';
import { ExpoPushMessage, PushTicket, FindTokensRequest } from 'src/types';
import { ExpoPushMessage, PushTicket, FindTokensRequest, DiscountNotificationRequest, RequestMatchNotificationRequest } from 'src/types';
import { NotifService } from '../../services/NotifService';

@JsonController('notif/')
Expand All @@ -14,5 +14,15 @@ export class NotifController {
async sendNotif(@Body() findTokensRequest: FindTokensRequest) {
return this.notifService.sendNotifs(findTokensRequest);
}

@Post('discount')
async sendDiscountNotif(@Body() discountRequest: DiscountNotificationRequest) {
return this.notifService.sendDiscountNotification(discountRequest);
}

@Post('request-match')
async sendRequestMatchNotif(@Body() matchRequest: RequestMatchNotificationRequest) {
return this.notifService.sendRequestMatchNotification(matchRequest);
}
}

8 changes: 8 additions & 0 deletions src/repositories/UserRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,14 @@ export class UserRepository extends AbstractRepository<UserModel> {
.getOne();
}

public async getUsersWhoSavedPost(postId: Uuid): Promise<UserModel[]> {
return await this.repository
.createQueryBuilder("user")
.leftJoin("user.saved", "saved_posts")
.where("saved_posts.id = :postId", { postId })
.getMany();
}

public async getUserByEmail(email: string): Promise<UserModel | undefined> {
return await this.repository
.createQueryBuilder("user")
Expand Down
121 changes: 120 additions & 1 deletion src/services/NotifService.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NotFoundError} from 'routing-controllers';
import { Service } from 'typedi';
import { ExpoPushMessage, PushTicket, FindTokensRequest, NotifSent } from '../types';
import { ExpoPushMessage, PushTicket, FindTokensRequest, NotifSent, DiscountNotificationRequest, RequestMatchNotificationRequest } from '../types';
import { Expo } from 'expo-server-sdk';
import { UserRepository } from 'src/repositories/UserRepository';
import Repositories, { TransactionsManager } from '../repositories';
Expand All @@ -24,6 +24,8 @@ export class NotifService {
// * @param {Object} expoServer the server object to connect with
// */

// Comment to push main

public sendNotifChunks = async (notifs : ExpoPushMessage[], expoServer : Expo) => {
let chunks = expoServer.chunkPushNotifications(notifs);
let tickets = [];
Expand Down Expand Up @@ -81,4 +83,121 @@ export class NotifService {
console.log(err) }
})
}

public async sendDiscountNotification(request: DiscountNotificationRequest) {
return this.transactions.readWrite(async (transactionalEntityManager) => {
const postRepository = Repositories.post(transactionalEntityManager);
const userRepository = Repositories.user(transactionalEntityManager);

// Get the post
const post = await postRepository.getPostById(request.listingId);
if (!post) {
throw new NotFoundError("Post not found!");
}

// Get all users who saved this post
const usersWithSavedPost = await userRepository.getUsersWhoSavedPost(post.id);

for (const user of usersWithSavedPost) {
const userSessionRepository = Repositories.session(transactionalEntityManager);
const allDeviceTokens = [];
const allsessions = await userSessionRepository.getSessionsByUserId(user.id);

for (var sess of allsessions) {
if (sess.deviceToken) {
allDeviceTokens.push(sess.deviceToken);
}
}

if (allDeviceTokens.length > 0) {
const discountPercentage = Math.round(
((request.oldPrice - request.newPrice) / request.oldPrice) * 100
);

let notif: ExpoPushMessage = {
to: allDeviceTokens,
sound: 'default',
title: 'Price Drop Alert! 🎉',
body: `A post you saved is now ${discountPercentage}% off!`,
data: {
postId: request.listingId,
oldPrice: request.oldPrice,
newPrice: request.newPrice
} as unknown as JSON
};

try {
let notifs: ExpoPushMessage[] = [];
notif.to.forEach(token => {
notifs.push({
to: [token],
sound: 'default',
title: notif.title,
body: notif.body,
data: notif.data
});
});
await this.sendNotifChunks(notifs, expoServer);
} catch (err) {
console.log(err);
}
}
}
});
}

public async sendRequestMatchNotification(request: RequestMatchNotificationRequest) {
return this.transactions.readWrite(async (transactionalEntityManager) => {
const postRepository = Repositories.post(transactionalEntityManager);
const requestRepository = Repositories.request(transactionalEntityManager);

const post = await postRepository.getPostById(request.listingId);
const userRequest = await requestRepository.getRequestById(request.requestId);

if (!post || !userRequest) {
throw new NotFoundError("Post or Request not found!");
}

const userSessionRepository = Repositories.session(transactionalEntityManager);
const allDeviceTokens = [];
const allsessions = await userSessionRepository.getSessionsByUserId(request.userId);

for (var sess of allsessions) {
if (sess.deviceToken) {
allDeviceTokens.push(sess.deviceToken);
}
}

if (allDeviceTokens.length > 0) {
let notif: ExpoPushMessage = {
to: allDeviceTokens,
sound: 'default',
title: 'Request Match Found! 🎯',
body: `We found a post that matches your request for ${userRequest.title}`,
data: {
postId: request.listingId,
requestId: request.requestId,
postTitle: post.title,
price: post.original_price
} as unknown as JSON
};

try {
let notifs: ExpoPushMessage[] = [];
notif.to.forEach(token => {
notifs.push({
to: [token],
sound: 'default',
title: notif.title,
body: notif.body,
data: notif.data
});
});
await this.sendNotifChunks(notifs, expoServer);
} catch (err) {
console.log(err);
}
}
});
}
}
15 changes: 14 additions & 1 deletion src/services/PostService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@ import { CreatePostRequest, FilterPostsRequest, FilterPostsByPriceRequest, Filte
import { uploadImage } from '../utils/Requests';
import { getLoadedModel } from '../utils/SentenceEncoder';
import { PostRepository } from 'src/repositories/PostRepository';
import { FindTokensRequest } from '../types';
import { NotifService } from './NotifService';
require('@tensorflow-models/universal-sentence-encoder')

@Service()
export class PostService {
private transactions: TransactionsManager;

constructor(@InjectManager() entityManager: EntityManager) {
this.transactions = new TransactionsManager(entityManager);
}
Expand Down Expand Up @@ -266,6 +268,17 @@ export class PostService {
if (!post) throw new NotFoundError('Post not found!');
if (post.user.isActive == false) throw new NotFoundError('User is not active!');
const userRepository = Repositories.user(transactionalEntityManager);
const postOwner = await userRepository.getUserById(post.user.id);
if (!postOwner) throw new NotFoundError('Post owner not found!');
const bookmarkNotifRequest: FindTokensRequest =
{
email: postOwner.email,
title: "Bookmark Listing Notification",
body: user.username + " bookmarked your listing!",
data: {} as JSON
}
const notifService = new NotifService(transactionalEntityManager);
await notifService.sendNotifs(bookmarkNotifRequest);
return await userRepository.savePost(user, post);
});
}
Expand Down
13 changes: 13 additions & 0 deletions src/types/ApiRequests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,19 @@ export interface FindTokensRequest {
data: JSON;
}

export interface DiscountNotificationRequest {
listingId: Uuid;
oldPrice: number;
newPrice: number;
sellerId: Uuid;
}

export interface RequestMatchNotificationRequest {
requestId: Uuid;
listingId: Uuid;
userId: Uuid;
}

// REPORTS
export interface ReportPostRequest {
reported: Uuid;
Expand Down

0 comments on commit 0265073

Please sign in to comment.