Untitled
unknown
plain_text
a year ago
13 kB
9
Indexable
const mongoose = require('mongoose');
const User = require('../Models/userModel.js');
const SubCategory = require('../Models/subcategoryModel.js');
const Group = require('../Models/groupModel.js');
const Brand = require('../Models/brandModel.js');
const Category = require('../Models/categoryModel.js');
const Product = require('../Models/productModel.js');
const AppError = require('../utils/appError.js');
const catchAsync = require('../utils/catchAsync.js');
const { isDecimal } = require('validator');
const Client = require('../Models/clientModel.js');
const Cart = require('../Models/cartModel.js');
const Order = require('../Models/orderModel.js');
const Retailer = require('../Models/retailerModel.js');
const valid = require('../utils/validationfunctions.js');
exports.getRecentOrders = catchAsync(async (req, res, next) => {
let filter = {}
if(req.user.role == "salesman"){
filter.sales_man = req.user._id
}
const results = await Order.aggregate([
{ $match: {filter}},
{ $sort: { createdAt: -1 } },
{ $limit: 6 },
{
$lookup: {
from: 'products',
localField: 'products.0.product',
foreignField: '_id',
pipeline: [{ $project: { name: 1, images: 1 } }],
as: 'product'
}
},
{
$lookup: {
from: 'users',
localField: 'ordered_by',
foreignField: '_id',
pipeline: [{ $project: { name: 1 } }],
as: 'clientName'
}
},
]);
// console.log(results.explain("executionStats"))
const data = results.reduce((result, order) => {
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;
}, []);
res.status(200).json({ status: 'success', data: data });
});
exports.getRecentClients = catchAsync(async (req, res, next) => {
let search = {role : "client"}
const results = await User.aggregate([
{ $match : {role : "client"}},
{ $sort: { createdAt: -1 } },
{ $limit: 6 },
{
$lookup: {
from: 'clients',
localField: 'profile',
foreignField: '_id',
pipeline: [
{
$lookup: {
from: 'orders',
localField: 'orders',
foreignField: '_id',
pipeline: [
{
$group: {
_id: "",
balance: { $sum: "$totalPrice" }
}
},],
as: 'amount'
}
},
],
as: 'client'
}
},
]);
const data = results.reduce((result, client) => {
let obj = {};
obj._id = client._id;
obj.name = client.name;
obj.amount = client.client[0]?.amount[0]?.balance ?? 0;
obj.profileImage = client.photo;
result.push(obj);
return result;
}, []);
res.status(200).json({
status: "success",
data: data
});
})
exports.getRecentRetailers = catchAsync(async (req, res, next) => {
let filter = {role : "retailer"}
if(req.user.role == "salesman"){
filter.sales_man = req.user._id
}
const results = await User.aggregate([
{ $match : filter},
{ $sort: { createdAt: -1 } },
{ $limit: 6 },
{
$lookup: {
from: 'retailers',
localField: 'profile',
foreignField: '_id',
pipeline: [
{
$lookup: {
from: 'orders',
localField: 'orders',
foreignField: '_id',
pipeline: [
{
$group: {
_id: "",
balance: { $sum: "$totalPrice" }
}
},],
as: 'amount'
}
},
],
as: 'retailer'
}
},
]);
const data = results.reduce((result, retailer) => {
let obj = {};
obj._id = retailer._id;
obj.name = retailer.name;
obj.amount = retailer.retailer[0]?.amount[0]?.balance ?? 0;
obj.profileImage = retailer.photo;
result.push(obj);
return result;
}, []);
res.status(200).json({
status: "success",
data: data
});
})
exports.getRecentRetailersForSalesMan = catchAsync(async (req, res, next) => {
const results = await Retailer.aggregate([
{ $match: {sales_man: req.user._id}},
{ $sort: { createdAt: -1 } },
{
$lookup: {
from: 'orders',
localField: 'orders',
foreignField: '_id',
pipeline: [
{
$group: {
_id: "",
balance: { $sum: "$totalPrice" }
}
},],
as: 'amount'
}
},
{
$lookup: {
from: 'retailers',
localField: 'profile',
foreignField: '_id',
as: 'user'
}
}
])
const data = results.reduce((result, retailer) => {
let obj = {};
obj._id = retailer._id;
obj.name = retailer.user[0].name;
obj.amount = retailer.amount[0]?.balance ?? 0;
obj.profileImage = retailer.user[0].photo;
result.push(obj);
return result;
}, []);
res.status(200).json({
status: "success",
data: data
});
})
exports.getOrdersByCategories = catchAsync(async (req, res, next) => {
let filter = {}
if(req.user.role == "salesman"){
filter.sales_man = req.user._id
}
const results = await Order.aggregate([
{ $match: filter},
{ $unwind : '$products'},
{
$lookup: {
from: 'products',
localField: 'products.product',
foreignField: '_id',
pipeline: [
{
$lookup: {
from: 'categories',
localField: 'categories',
foreignField: '_id',
pipeline: [
{ $project: { category: 1} }],
as: 'category'
}
},
// { $project: { categories: 1} },
// { $unwind : '$category'},
],
as: 'products.product'
},
},
{
$group: {
_id:"$products.product.category" , // Grouping by category
totalOrders: { $sum: "$products.quantity" } // Counting the orders in each category
}
}
]);
const data = results.reduce((result, category) => {
let obj = {};
obj._id = category._id._id;
obj.name = category._id[0][0]?.category;
obj.totalOrders = category.totalOrders;
result.push(obj);
return result;
}, []);
res.status(200).json({
status: "success",
data: data
});
})
exports.getTotalSales = catchAsync(async (req, res, next) => {
const {startDate, endDate, limitDate } = req.body;
let filter = {}
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);
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);
if (start_date == 'Invalid Date' || end_date == 'Invalid Date') {
return next(new AppError('Invalid Date', 400));
}
filter.createdAt = { $gte: start_date, $lte: end_date };
}
if(req.user.role == "salesman"){
filter.sales_man = req.user._id
}
const totalSales = await Order.aggregate([
{ $match : filter},
{
$group: {
_id:"" , // Grouping by category
total: { $sum: "$totalPrice" },
}
}
]);
const totalProfit = await Order.aggregate([
{ $match : filter},
{ $unwind : "$products"},
{
$group: {
_id:"" ,
Profit: { $sum: { $multiply: ["$products.quantity",{ $subtract: [ "$products.price", "$products.initialPrice" ] } ] } }
}
}
]);
const totalCustomers = await Order.aggregate([
{ $match : filter},
{
$group: {
_id:"$ordered_by" , // Grouping by category
}
}
]);
const totalProducts = await Order.aggregate([{ $match: filter }, { $unwind: '$products' }]);
const totalOrders = await Order.find(filter)?.count();
const data = {};
data.totalOrders = totalOrders || 0;
data.totalSales = Number.parseFloat(totalSales[0]?.total).toFixed(2) || 0;
data.totalProfite = Number.parseFloat(totalProfit[0]?.Profit).toFixed(2) || 0;
data.totalCustomers = totalCustomers?.length || 0;
data.totalProducts = totalProducts?.length || 0;
res.status(200).json({
status: "success",
data: data
});
})
exports.getTotalByStatus = catchAsync(async (req, res, next) => {
const {startDate, endDate, limitDate } = req.body;
let filter = {}
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);
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);
if (start_date == 'Invalid Date' || end_date == 'Invalid Date') {
return next(new AppError('Invalid Date', 400));
}
filter.createdAt = { $gte: start_date, $lte: end_date };
}
if(req.user.role == "salesman"){
filter.sales_man = req.user._id
}
const total = await Order.aggregate([
{ $match : filter},
{
$group: {
_id:"$status" ,
total: { $sum: 1 }
}
}
]);
const data = total.reduce((result,element) => {
if(element._id == "pending"){
result.pending = element.total
}
if(element._id == "cancel"){
result.cancel = element.total
}
if(element._id == "delivered"){
result.delivered = element.total
}
if(element._id == "processing"){
result.processing = element.total
}
return result
},{})
res.status(200).json({
status: "success",
data: data
});
})
exports.getCustomersTransactions = catchAsync(async (req, res, next) => {
const {startDate, endDate, limitDate } = req.body;
let filter = {}
var currentDate = new Date();
currentDate.setDate(currentDate.getDate() - 7);
filter.createdAt = { $gte: currentDate };
if(req.user.role == "salesman"){
filter.sales_man = req.user._id
}
const total = await Order.aggregate([
{ $match : filter},
{
$group: {
_id: { dayOfWeek: { $dayOfWeek: "$createdAt" },
customers : "$ordered_by" } ,
totalOrdersByCust: { $sum: 1 }
}
},
{
$group: {
_id: "$_id.dayOfWeek" ,
totalOrders: { $sum: "$totalOrdersByCust" },
totalCustomers : { $sum: 1 }
}
}
]);
res.status(200).json({
status: "success",
data: total
});
})
Editor is loading...
Leave a Comment