Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat:小鈴鐺通知 #104

Merged
merged 5 commits into from
May 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions connections/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const initCategories = require('../db/initCategories');
const initPlans = require('../db/initPlans');
const initTasks = require('../db/initTasks');
const initReviews = require('../db/initReviews');
const initNotify = require('../db/initNotify');
const initUsers = require('../db/initUsers');
const initTransactions = require('../db/initTransactions');
const initSuperhandyReviews = require('../db/initSuperhandyReviews');
Expand All @@ -21,6 +22,7 @@ mongoose
await initTasks();
await initTransactions();
await initReviews();
await initNotify();
await initSuperhandyReviews();
})
.catch((err) => console.error('資料庫連接失敗', err));
55 changes: 55 additions & 0 deletions controller/notifyController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const mongoose = require('mongoose');
const { appError, handleErrorAsync } = require('../utils/errorHandler');
const getHttpResponse = require('../utils/successHandler');
const Notify = require('../models/notifyModel');

const notify = {
getNotifyList: handleErrorAsync(async (req, res, next) => {
const userId = req.user._id;
const notifications = await Notify.find({ userId: userId }, { __v: 0 })
.sort({ createdAt: -1 }).lean();

const transformedNotifications = notifications.map(notification => {
return { notifyId: notification._id, ...notification };
});
delete transformedNotifications._id;
res.status(200).json(
getHttpResponse({
message: '取得通知成功',
data: transformedNotifications,
}),
);
}),
markRead: handleErrorAsync(async (req, res, next) => {
const userId = req.user._id;
const notifyId = req.params.notifyId;
const notify = await Notify.findOne({ _id: notifyId });
if (!mongoose.isValidObjectId(notifyId)) {
return next(appError(400, '40104', 'Id 格式錯誤'));
}
if (!notify) {
return next(appError(404, '40212', '查無此通知'));
}
if (notify.userId.toString() !== userId.toString()) {
return next(appError(403, '40302', '沒有權限'));
}
if (notify.read) {
return next(appError(404, '40213', '該通知已經已讀了'));
}
await Notify.findOneAndUpdate(
{ _id: notifyId },
{
$set: {
read: true,
},
},
);
res.status(200).json(
getHttpResponse({
message: '已讀通知成功',
}),
);
}),
};

module.exports = notify;
25 changes: 24 additions & 1 deletion controller/taskController.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const User = require('../models/userModel');
const Task = require('../models/taskModel');
const TaskTrans = require('../models/taskTransModel');
const TaskValidator = require('../service/taskValidator');
const Notify = require('../models/notifyModel');
const getexposurePlanPrices = require('../service/exposurePlan');
const geocoding = require('../utils/geocoding');

Expand Down Expand Up @@ -415,7 +416,29 @@ const tasks = {
if (task.status !== 'published') {
return next(appError(405, '40214', `任務狀態錯誤 ${task.status}`));
}
// 這邊需要發送幫手被踢除的推播
// 推播通知
const helpers = task.helpers;
const notifications = helpers.map(helper => {
const helpId = helper.helperId;
return {
userId: helpId,
tag: '幫手通知',
read: true,
description: `您待媒合的任務:「${task.title} 」已下架`,
taskId: taskId,
createdAt: Date.now(),
};
});
await Notify.insertMany(notifications);
await Notify.create({
userId: req.user._id,
tag: '案主通知',
read: true,
description: `您待媒合的任務:「${task.title} 」已下架,無法被其他人查看該任務`,
taskId: taskId,
createdAt: Date.now(),
})
// 更新 Task
await Task.findOneAndUpdate(
{ _id: taskId },
{
Expand Down
121 changes: 121 additions & 0 deletions db/initNotify.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
const Notify = require('../models/notifyModel');
const Task = require('../models/taskModel');
const User = require('../models/userModel');

const initNotify = async () => {
try {
// 刪除現有的所有類別
await Notify.deleteMany({});
const tasks = await Task.find().select('userId');
const userCase1 = await User.findOne({ email: '[email protected]' }).select('lastName firstName phone');
const userCase2 = await User.findOne({ email: '[email protected]' }).select('lastName firstName phone');
const userCase3 = await User.findOne({ email: '[email protected]' }).select('lastName firstName phone');
const userCase5 = await User.findOne({ email: '[email protected]' }).select('lastName firstName phone');
const taskCase1 = tasks.find((task) => task.userId._id.equals(userCase1._id));

const notify = [
{
userId: userCase5._id,
tag: '幫手通知',
read: true,
description: '您媒合的任務:「陪我家狗玩 」成功,您可以進行任務囉!',
taskId: taskCase1._id,
createdAt: new Date('2022-02-16T13:34:56'),
},
{
userId: userCase3._id,
tag: '幫手通知',
read: true,
description: '您媒合的任務:「陪我家狗玩 」失敗',
taskId: taskCase1._id,
createdAt: new Date('2022-02-16T13:34:56'),
},
{
userId: userCase2._id,
tag: '幫手通知',
read: true,
description: '您媒合的任務:「陪我家狗玩 」失敗',
taskId: taskCase1._id,
createdAt: new Date('2022-02-16T13:34:56'),
},
{
userId: userCase1._id,
tag: '案主通知',
read: true,
description: '您媒合的任務:「陪我家狗玩 」成功,幫手可以進行任務囉!',
taskId: taskCase1._id,
createdAt: new Date('2022-02-16T13:34:56'),
},
{
userId: userCase5._id,
tag: '幫手通知',
read: true,
description: '您的任務:「陪我家狗玩 」已經提交驗收!',
taskId: taskCase1._id,
createdAt: new Date('2022-02-17T13:55:56'),
},
{
userId: userCase1._id,
tag: '案主通知',
read: true,
description: '您的任務:「陪我家狗玩 」幫手已提交驗收內容,請進行驗收',
taskId: taskCase1._id,
createdAt: new Date('2022-02-17T13:55:56'),
},
{
userId: userCase5._id,
tag: '幫手通知',
read: true,
description: '您的任務:「陪我家狗玩 」案主已驗收完成,後續系統將自動提撥款項,並請進行評價',
taskId: taskCase1._id,
createdAt: new Date('2022-02-19T19:15:50'),
},
{
userId: userCase1._id,
tag: '案主通知',
read: false,
description: '您的任務:「陪我家狗玩 」 已結案,後續系統將自動提撥款項給幫手,並請進行評價',
taskId: taskCase1._id,
createdAt: new Date('2022-02-19T19:15:50'),
},
{
userId: userCase5._id,
tag: '幫手通知',
read: false,
description: '您的任務:「陪我家狗玩 」,案主給您評價囉!',
taskId: taskCase1._id,
createdAt: new Date('2022-02-22T08:19:50'),
},
{
userId: userCase1._id,
tag: '案主通知',
read: false,
description: '您的任務:「陪我家狗玩 」 ,幫手給您評價囉!',
taskId: taskCase1._id,
createdAt: new Date('2022-02-23T08:19:50'),
},
{
userId: userCase1._id,
tag: '系統通知',
read: false,
description: '端午節點數大贈送,點我了解更多',
createdAt: new Date('2023-05-15T08:19:50'),
},
{
userId: userCase1._id,
tag: '系統通知',
read: false,
description: '系統儲值成功',
createdAt: new Date('2023-05-01T08:19:50'),
},
];

// 插入新的類別
await Notify.insertMany(notify);
console.log('通知資料初始化成功');
} catch (err) {
console.error('通知資料初始化失敗', err);
}
};

module.exports = initNotify;
2 changes: 1 addition & 1 deletion db/initTasks.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ const initTasks = async () => {
status: 'unpaired',
},
{
helperId: userCase1._id,
helperId: userCase2._id,
status: 'unpaired',
},
],
Expand Down
35 changes: 35 additions & 0 deletions models/notifyModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const mongoose = require('mongoose');
const notifySchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
},
tag: {
type: String,
required: true,
enum: ['案主通知', '幫手通知', '系統通知']
},
read: {
type: Boolean,
default: false,
required: true
},
description: {
type: String,
required: true,
trim: true,
},
taskId: {
type: String,
required: false,
},
createdAt: {
type: Date,
default: Date.now,
},
});

const Notify = mongoose.model('notification', notifySchema);

module.exports = Notify;
1 change: 0 additions & 1 deletion routes/account.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
var express = require('express');
var router = express.Router();
const User = require('../models/userModel');
const accountController = require('../controller/accountController');

router.get('/profile', async function (req, res, next) {
Expand Down
2 changes: 2 additions & 0 deletions routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const accountRouter = require('./account');
const homeRouter = require('./home');
const generalRouter = require('./general');
const postTaskRouter = require('./postTask');
const notifyRouter = require('./notify');
const { isAuth } = require('../middleware/auth');
/** 生成 Swagger 套件 */
const swaggerUI = require('swagger-ui-express');
Expand All @@ -14,5 +15,6 @@ module.exports = (app) => {
app.use('/home', homeRouter);
app.use('/general', generalRouter);
app.use('/post-task', isAuth, postTaskRouter);
app.use('/notifications', isAuth, notifyRouter);
app.use('/api-doc', swaggerUI.serve, swaggerUI.setup(swaggerFile));
};
41 changes: 41 additions & 0 deletions routes/notify.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
var express = require('express');
var router = express.Router();
const notifyController = require('../controller/notifyController');

/* 取得通知清單 */
router.get('/list', function (req, res, next) {
/**
* #swagger.tags = ['Notifications']
* #swagger.summary = '取得通知清單 (Get all notifications)'
* #swagger.security=[{"Bearer": []}]
/**
#swagger.responses[200] = {
description: '取得通知成功',
schema: { $ref: '#/definitions/getNotifyList' }
}
#swagger.responses[500] = {
description: '系統錯誤',
schema: { $ref: '#/definitions/Error500' }
}
*/
notifyController.getNotifyList(req, res, next);
});
/* 將某個通知標記為已讀 */
router.patch('/read/:notifyId', function (req, res, next) {
/**
* #swagger.tags = ['Notifications']
* #swagger.summary = '將某個通知標記為已讀 (Mark a notification as read)'
* #swagger.security=[{"Bearer": []}]
/**
#swagger.responses[200] = {
description: '已讀通知成功'
}
#swagger.responses[500] = {
description: '系統錯誤',
schema: { $ref: '#/definitions/Error500' }
}
*/
notifyController.markRead(req, res, next);
});

module.exports = router;
14 changes: 14 additions & 0 deletions swagger-defintion.js
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,19 @@ const cashbackPoints = {
message: '返還成功',
};

const getNotifyList = {
status: 'success',
data: {
userId: "646266a3d7d8ce5010f8c327",
tag: "案主通知",
read: true,
description: "您的任務:「陪我家狗玩 」幫手已提交驗收內容,請進行驗收",
taskId: "646266a3d7d8ce5010f8c334",
createdAt: "2022-02-17T05:55:56.000Z"
},
message: '取得通知成功',
};

module.exports = {
Success,
Error400,
Expand Down Expand Up @@ -344,4 +357,5 @@ module.exports = {
unpublishEditDetail,
purchasePoints,
cashbackPoints,
getNotifyList
};
Loading