Skip to content

Commit

Permalink
Merge pull request #72 from atlp-rwanda/ft-notifications
Browse files Browse the repository at this point in the history
[Finishes #187355128] ft-notifications
  • Loading branch information
UmuhireJessie authored Jul 21, 2024
2 parents 62f07e9 + 43979a7 commit 7302011
Show file tree
Hide file tree
Showing 27 changed files with 2,120 additions and 143 deletions.
38 changes: 35 additions & 3 deletions src/controllers/productController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,19 @@ import { Console, log } from 'console';
import { logger } from 'sequelize/types/utils/logger';
import upload from '../middleware/multer';
import { UploadApiResponse, ResourceType } from 'cloudinary';

interface User {
import { addCollectionEmitter } from '../utils/notifications/addCollectionHandler';
import { addProductEmitter } from '../utils/notifications/addProductHandler';
import { updateProductEmitter } from '../utils/notifications/updateProductHandler';
import { saveCollectionToDbEmitter } from '../utils/notifications/saveCollectionToDbHandler';
import { saveStatusToDbEmitter } from '../utils/notifications/saveStatusToDbHandler';
import { saveProductToDbEmitter } from '../utils/notifications/saveProductToDbHandler';

export interface User {
role: string;
userId: string;
userproductId: string;
email: string;
firstName: string;
}

export interface CustomRequest extends Request {
Expand Down Expand Up @@ -57,6 +65,19 @@ export async function createCollection(req: CustomRequest, res: Response) {
sellerId: sellerId,
});

addCollectionEmitter.emit('add', {
userId: req.user?.userId,
firstName: req.user?.firstName,
email: req.user?.email,
collectionName: collection.name,
created: collection.createdAt,
});

saveCollectionToDbEmitter.emit('save', {
userId: req.user?.userId,
collectionName: collection.name,
});

return res.status(201).json(collection);
} catch (error) {
return res.status(500).json({ error: 'Internal Server Error' });
Expand All @@ -65,6 +86,7 @@ export async function createCollection(req: CustomRequest, res: Response) {

export async function createProduct(req: CustomRequest, res: Response) {
try {
const userInfo = req.user;
const { collectionId } = req.params;
const { name, price, category, quantity, expiryDate, bonus } = req.body;

Expand Down Expand Up @@ -121,6 +143,10 @@ export async function createProduct(req: CustomRequest, res: Response) {
collectionId,
});

//productEmitter.emit('created', { product, userInfo });

addProductEmitter.emit('add', { product, userInfo });
saveProductToDbEmitter.emit('save', { product, userInfo });
return res
.status(201)
.json({ message: 'Product added successfully', product });
Expand Down Expand Up @@ -187,7 +213,7 @@ export class ProductController {
}
}

static async updateSingleProduct(req: Request, res: Response) {
static async updateSingleProduct(req: CustomRequest, res: Response) {
try {
const { productId } = req.params;
if (!productId) {
Expand All @@ -209,6 +235,12 @@ export class ProductController {
{ where: { productId } },
);

const productStatus = newStatus ? 'Available' : 'Not available';
const userInfo = req.user;

updateProductEmitter.emit('update', { product, userInfo, productStatus });
saveStatusToDbEmitter.emit('save', { product, userInfo, productStatus });

res.status(200).json({
message: `Product is successfully marked as ${newStatus ? 'available' : 'unavailable'}`,
isAvailable: newStatus,
Expand Down
64 changes: 63 additions & 1 deletion src/controllers/userControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,6 @@ export default class UserController {
});
}
}

static async setUserRoles(req: Request, res: Response) {
try {
const { role } = req.body;
Expand Down Expand Up @@ -553,6 +552,69 @@ export default class UserController {
});
}
}

static async getNotifications(req: any, res: Response) {
const { token } = req;

try {
const getDecodedToken = jwt.verify(token, secret);
const userId = getDecodedToken.userId;
const allNotifications = await db.Notifications.findAll({
where: { userId: userId },
});

if (!allNotifications) {
return res.status(404).json({
status: 'fail',
message: 'No notification found',
});
}

return res.status(200).json({
status: 'Success',
data: allNotifications,
});
} catch (e) {
res.status(500).json({
status: 'fail',
message: 'something went wrong: ' + e,
});
}
}
static async getSingleNotification(req: any, res: Response) {
const { token } = req;
const { notificationId } = req.body;

try {
const getDecodedToken = jwt.verify(token, secret);
const userId = getDecodedToken.userId;
const singleNotification = await db.Notifications.findOne({
where: {
userId: userId,
notificationId: notificationId,
},
});

if (singleNotification) {
singleNotification.isRead = true;
await singleNotification.save();
return res.status(200).json({
status: 'Success',
data: singleNotification,
});
} else {
return res.status(404).json({
status: 'fail',
message: 'No notification found',
});
}
} catch (e) {
res.status(500).json({
status: 'fail',
message: 'something went wrong: ' + e,
});
}
}
}

dotenv.config();
Expand Down
45 changes: 45 additions & 0 deletions src/database/migrations/20240618115609-create_notifications.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
'use strict';
import { QueryInterface } from 'sequelize';
import { DataTypes, Sequelize } from 'sequelize';
module.exports = {
async up(queryInterface: QueryInterface, Sequelize: Sequelize) {
await queryInterface.createTable('Notifications', {
notificationId: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID, // Using Sequelize's UUID data type
defaultValue: Sequelize.literal('uuid_generate_v4()'), // Assuming you have a UUID extension in PostgreSQL
},
userId: {
allowNull: false,
type: DataTypes.STRING,
},
subject: {
allowNull: false,
type: DataTypes.STRING,
},
body: {
allowNull: false,
type: DataTypes.STRING,
},
isRead: {
allowNull: false,
type: DataTypes.BOOLEAN,
},
createdAt: {
allowNull: false,
type: DataTypes.DATE,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
},
updatedAt: {
allowNull: false,
type: DataTypes.DATE,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
},
});
},

async down(queryInterface: QueryInterface, Sequelize: Sequelize) {
await queryInterface.dropTable('Notifications');
},
};
56 changes: 56 additions & 0 deletions src/database/models/notifications.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
'use strict';
const { Model } = require('sequelize');
module.exports = (
sequelize: any,
DataTypes: {
UUID: any;
UUIDV4: any;
STRING: any;
DECIMAL: any;
BOOLEAN: any;
ARRAY: any;
DATE: any;
INTEGER: any;
},
) => {
class Notifications extends Model {}
Notifications.init(
{
notificationId: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
},

userId: {
allowNull: false,
type: DataTypes.STRING,
},
subject: {
allowNull: false,
type: DataTypes.STRING,
},
body: {
allowNull: false,
type: DataTypes.STRING,
},
isRead: {
allowNull: false,
type: DataTypes.BOOLEAN,
defaultValue: false,
},

updatedAt: {
allowNull: false,
type: DataTypes.DATE,
defaultValue: Date.now(),
},
},
{
sequelize,
modelName: 'Notifications',
},
);
return Notifications;
};
Loading

0 comments on commit 7302011

Please sign in to comment.