Untitled
unknown
plain_text
7 months ago
3.0 kB
3
Indexable
Never
const getPromos = async (req, res) => { try { const limit = parseInt(req.query.limit) || 10; const page = parseInt(req.query.page) || 1; const skip = (page - 1) * limit; const sortField = req.query.id || 'createdAt'; const sortOrder = req.query.desc === 'false' ? 1 : -1; const searchTerm = req.query.search || ''; const projection = { twinId: 1, name: 1, type: 1, status: 1, duration_start_at: 1, duration_end_at: 1, nominal_type: 1, nominal_value: 1, voucher_code: 1, duration_status: 1, }; const filters = { deletedAt: null, $or: [{ twinId: { $regex: searchTerm, $options: 'i' } }, { name: { $regex: searchTerm, $options: 'i' } }, { type: parseInt(searchTerm) || 0 }], }; const startQuery = formatDate(req.query.duration_start_at); const endQuery = formatDate(req.query.duration_end_at); if (req.query.duration_start_at) filters.duration_start_at = { $gte: startQuery }; if (req.query.duration_end_at) filters.duration_end_at = { $lte: endQuery }; const promos = await Promo.find(filters, projection).sort({ [sortField]: sortOrder }); // .skip(skip) // .limit(limit); // console.log(limit, skip); let updatedPromos = []; for (const promo of promos) { const currentDate = new Date(); const currentTimezoneOffsetInMilliseconds = currentDate.getTimezoneOffset() * 60000; const GMT7OffsetInMilliseconds = 7 * 60 * 60000; const currentDateGMT7 = new Date(currentDate.getTime() + currentTimezoneOffsetInMilliseconds + GMT7OffsetInMilliseconds); let promoStatus; if (promo.status === true) { const startTimestamp = new Date(promo.duration_start_at); const endTimestamp = new Date(promo.duration_end_at); if (startTimestamp > currentDateGMT7 && endTimestamp > currentDateGMT7) { promoStatus = 0; } else if (startTimestamp < currentDateGMT7 && endTimestamp > currentDateGMT7) { promoStatus = 2; } else if (startTimestamp < currentDateGMT7 && endTimestamp < currentDateGMT7) { promoStatus = 3; } } else if (promo.status === false) { promoStatus = 1; } await Promo.findOneAndUpdate({ twinId: promo.twinId }, { duration_status: promoStatus }, { new: true }).exec(); updatedPromos.push({ ...promo.toObject(), duration_status: promoStatus, }); } if (req.query.duration_status) { const durationStatusFilter = req.query.duration_status.split(',').map((status) => parseInt(status.trim())); updatedPromos = updatedPromos.filter((promo) => { return durationStatusFilter.includes(promo.duration_status); }); } const resultPomos = updatedPromos.slice(skip, skip + limit); const total = updatedPromos.length; const all_data = await Promo.countDocuments(filters); return res.status(200).json({ status: 'Success', data: resultPomos, pagination: { limit: limit, page: page, total: total, all_data: all_data, }, }); } catch (error) { return res.status(500).json({ status: 'error', message: error.message, }); } };
Leave a Comment