full
This commit is contained in:
87
controllers/panel/suggestions/suggestionsController.js
Normal file
87
controllers/panel/suggestions/suggestionsController.js
Normal file
@@ -0,0 +1,87 @@
|
||||
const UserSuggestionModel = require('../../../models/UserSuggestionModel')
|
||||
const jMoment = require('moment-jalaali')
|
||||
|
||||
const STATUS_LABELS = {
|
||||
new: 'جدید',
|
||||
in_progress: 'در حال انجام',
|
||||
done: 'انجام شده',
|
||||
rejected: 'رد شده'
|
||||
}
|
||||
|
||||
const formatSuggestion = (item) => ({
|
||||
...item._doc,
|
||||
statusLabel: STATUS_LABELS[item.status] || STATUS_LABELS.new,
|
||||
createdAt: jMoment(item.createdAt).format('jYYYY/jMM/jDD HH:mm')
|
||||
})
|
||||
|
||||
const getAllSuggestions = async (req, res) => {
|
||||
try {
|
||||
const { page = 1, limit = 20, search, status } = req.query
|
||||
const filter = {}
|
||||
|
||||
if (search) {
|
||||
filter.text = { $regex: search, $options: 'i' }
|
||||
}
|
||||
|
||||
if (status) {
|
||||
filter.status = status
|
||||
}
|
||||
|
||||
const options = {
|
||||
page: parseInt(page, 10) || 1,
|
||||
limit: parseInt(limit, 10) || 20,
|
||||
populate: [
|
||||
{
|
||||
path: 'user',
|
||||
select: '_id user_name first_name last_name mobile expertise'
|
||||
}
|
||||
],
|
||||
sort: { createdAt: -1 }
|
||||
}
|
||||
|
||||
const suggestions = await UserSuggestionModel.paginate(filter, options)
|
||||
const list = suggestions.docs.map(formatSuggestion)
|
||||
|
||||
res.json({
|
||||
suggestions: list,
|
||||
totalPages: suggestions.totalPages,
|
||||
totalItems: suggestions.totalDocs
|
||||
})
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
const updateSuggestionStatus = async (req, res) => {
|
||||
try {
|
||||
const { suggestionId } = req.params
|
||||
const { status } = req.body
|
||||
const allowed = ['new', 'in_progress', 'done', 'rejected']
|
||||
|
||||
if (!allowed.includes(status)) {
|
||||
return res.status(422).json({
|
||||
error: true,
|
||||
message: 'وضعیت نامعتبر است'
|
||||
})
|
||||
}
|
||||
|
||||
const suggestion = await UserSuggestionModel.findByIdAndUpdate(
|
||||
suggestionId,
|
||||
{ status },
|
||||
{ new: true }
|
||||
).populate('user', '_id user_name first_name last_name mobile expertise')
|
||||
|
||||
if (!suggestion) {
|
||||
return res.status(404).json({ message: 'پیشنهاد یافت نشد' })
|
||||
}
|
||||
|
||||
res.json({
|
||||
message: 'وضعیت بهروزرسانی شد',
|
||||
suggestion: formatSuggestion(suggestion)
|
||||
})
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { getAllSuggestions, updateSuggestionStatus, STATUS_LABELS }
|
||||
Reference in New Issue
Block a user