Untitled
exports.AddTrackingAndColis = catchAsync(async (req, res, next) => { const { tracking_number, colis_number, orderId } = req.body; const order = await Order.findById(toObjectId(orderId, next)) if(!order){ return next(new AppError('Order not found', 400)); } if(tracking_number){ order.nb_tracking = tracking_number } if(colis_number){ order.nb_colis = colis_number } await order.save() res.status(200).json({ message: 'success', data: order }); }); exports.filterOrders = catchAsync(async (req, res, next) => { const { category, status, startDate, endDate, limitDate } = req.body; const page = parseInt(req.query.page); const limit = parseInt(req.query.limit); if (!page || !limit) { return next(new AppError('page and limit required', 400)); } let category_filter = {}; let filter = {}; if (category) { const Id = toObjectId(category, next); let id_category = await Category.findById(Id); if (id_category) { //arrayAND.push({ categories: Id }); category_filter.categories = Id; } else { return next(new AppError('invalid categorie value', 400)); } } if (status == 'pending' || status == 'processing' || status == 'cancel' || status == 'delivered') { filter.status = status; } if (limitDate) { var currentDate = new Date(); let days = parseInt(limitDate); currentDate.setDate(currentDate.getDate() - days); filter.createdAt = { $gte: currentDate }; } if (startDate && !endDate) { let date = new Date(startDate); if (date == 'Invalid Date') { return next(new AppError('Invalid Date', 400)); } filter.createdAt = { $gte: date }; } if (!startDate && endDate) { let date = new Date(endDate); date.setDate(date.getDate()+1) if (date == 'Invalid Date') { return next(new AppError('Invalid Date', 400)); } filter.createdAt = { $lte: date }; } if (startDate && endDate) { let start_date = new Date(startDate); let end_date = new Date(endDate); end_date.setDate(end_date.getDate()+1) if (start_date == 'Invalid Date' || end_date == 'Invalid Date') { return next(new AppError('Invalid Date', 400)); } filter.createdAt = { $gte: start_date, $lte: end_date }; } const results = await Order.aggregate([ { $match: filter }, { $sort: { createdAt: -1 } }, { $lookup: { from: 'products', localField: 'products.product', foreignField: '_id', pipeline: [{ $match: category_filter }], as: 'product' } }, { $lookup: { from: 'users', localField: 'ordered_by', foreignField: '_id', pipeline: [{ $project: { name: 1 } }], as: 'clientName' } }, { $limit: (page - 1) * limit + limit }, { $skip: (page - 1) * limit } ]); const data = results.reduce((result, order) => { if (order.product.length > 0) { let obj = {}; obj.units = order.products.length; obj.id = order._id; obj.product = {}; obj.product.name = order.product[0]?.name; obj.product.image = order.product[0]?.images[0]; obj.price = order.totalPrice; obj.status = order.status; obj.clientName = order.clientName[0]?.name; result.push(obj); } return result; }, []); const count = await Order.find(filter).count(); res.status(200).json({ status: 'success', count, data }); }); exports.OrdersToExcel = catchAsync(async (req, res, next) => { const { category, status, startDate, endDate, limitDate } = req.query; let category_filter = {}; let filter = {}; if (category) { const Id = toObjectId(category, next); let id_category = await Category.findById(Id); if (id_category) { //arrayAND.push({ categories: Id }); category_filter.categories = Id; } else { return next(new AppError('invalid categorie value', 400)); } } if (status == 'pending' || status == 'processing' || status == 'cancel' || status == 'delivered') { filter.status = status; } if (limitDate) { var currentDate = new Date(); let days = parseInt(limitDate); currentDate.setDate(currentDate.getDate() - days); filter.createdAt = { $gte: currentDate }; } if (startDate && !endDate) { let date = new Date(startDate); if (date == 'Invalid Date') { return next(new AppError('Invalid Date', 400)); } filter.createdAt = { $gte: date }; } if (!startDate && endDate) { let date = new Date(endDate); date.setDate(date.getDate()+1) if (date == 'Invalid Date') { return next(new AppError('Invalid Date', 400)); } filter.createdAt = { $lte: date }; } if (startDate && endDate) { let start_date = new Date(startDate); let end_date = new Date(endDate); end_date.setDate(end_date.getDate()+1) if (start_date == 'Invalid Date' || end_date == 'Invalid Date') { return next(new AppError('Invalid Date', 400)); } filter.createdAt = { $gte: start_date, $lte: end_date }; console.log('date :',end_date) } const results = await Order.aggregate([ { $match: filter }, { $sort: { createdAt: -1 } }, { $lookup: { from: 'products', localField: 'products.product', foreignField: '_id', pipeline: [{ $match: category_filter }], as: 'product' } }, { $lookup: { from: 'users', localField: 'ordered_by', foreignField: '_id', pipeline: [{ $project: { name: 1 } }], as: 'clientName' } } ]); const flatData = results.map(order => { return { "Order ID": order._id.toString(), "First Name": order?.cart_address?.first_name, "Last Name": order?.cart_address?.last_name, "Phone": order?.cart_address?.phone, "City": order?.cart_address?.city, "Zip Code": order?.cart_address?.zipCode, "Address": order?.cart_address?.address, "Units": order?.products.length, "Total Price": order?.totalPrice, "Status": order.status, "Created At": formatDateToYYYYMMDD(order?.createdAt), "Updated At": formatDateToYYYYMMDD(order?.updatedAt), "Tracking Number": order?.nb_tracking, "Number of Parcels": order?.nb_colis } }).flat(); console.log(flatData) const worksheet = XLSX.utils.json_to_sheet(flatData); const workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, "Orders"); // Generate Excel file buffer const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' }); res.setHeader('Content-Disposition', 'attachment; filename="OrdersData.xlsx"'); res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); // Send the buffer as a response return res.send(excelBuffer); }); function formatDateToYYYYMMDD(date) { if(date){ if (!(date instanceof Date)) { throw new Error("Invalid date object"); } const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based, so add 1 const day = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; } }
Leave a Comment