I have this NodeJS code which I need to Reduce complexity and making it more readable coz it has to many repeatable loops, and the api is very slow how do i fix this.
const { PRISMA, moment, decodeHeader } = require('../../Config');
const { throwErrors } = require('../../GlobalFunctions');
const MOMENT = require('moment');
module.exports = async function (fastify) {
await fastify.post('/get-dashboard', async (req, res) => {
try {
const headerData = decodeHeader(req.headers);
if (headerData == 'error') {
res.status(401).send({
status: false,
status_code: 'FAILED',
message: 'UNAUTHORIZED',
});
} else {
// let ref = req.body?.ref ? req.body?.ref : '';
const location_id = req.body?.location_id ? req.body?.location_id : '';
const filter_by = req.body?.filter_by ? req.body?.filter_by : '';
const custom_startdate = req.body?.custom_startdate
? req.body?.custom_startdate
: '';
const custom_enddate = req.body?.custom_enddate
? req.body?.custom_enddate
: '';
// get custom start and end date
let custom_start_date =
MOMENT(custom_startdate).format('YYYY-MM-DD') + 'T00:00:00.000+00:00';
let custom_end_date = MOMENT(custom_enddate).format('YYYY-MM-DD') + 'T00:00:00.000+00:00';
// get current start and end date
let current_date =
MOMENT().format('YYYY-MM-DD') + 'T00:00:00.000+00:00';
//get start and end of the week
let startofweek_date =
MOMENT().startOf('week').format('YYYY-MM-DD') + 'T00:00:00.000+00:00';
let endofweek_date =
MOMENT().endOf('week').format('YYYY-MM-DD') + 'T00:00:00.000+00:00';
//get start and end of the month
let startOfMonth_date =
MOMENT().startOf('month').format('YYYY-MM-DD') +
'T00:00:00.000+00:00';
let endOfMonth_date =
MOMENT().endOf('month').format('YYYY-MM-DD') + 'T00:00:00.000+00:00';
// get start and end of the year
let startOfYear_date =
MOMENT().startOf('year').format('YYYY-MM-DD') + 'T00:00:00.000+00:00';
let endOftheYear_date =
MOMENT().endOf('year').format('YYYY-MM-DD') + 'T00:00:00.000+00:00';
// ```GRAPH CALCULATION FOR YEAR```\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
let query = '';
graph_data = '';
let startOfYear = MOMENT().startOf('year');
let monthsForYear = [];
let year = [];
// Create an array of dates representing the start of each month in the year
for (let index = 0; index <= 11; index++) {
const add1Month = MOMENT(startOfYear)
.add(index, 'month')
.format('YYYY-MM-DDTHH:mm:SS.000+00:00');
monthsForYear.push(add1Month);
}
// Get the actual amount for each month
let statements = [];
for (let i = 0; i < monthsForYear.length; i++) {
let j = i + 1;
statements.push(PRISMA.orders.findMany({
where: {
created_at: {
gte: monthsForYear[i],
lte:
i === monthsForYear.length - 1 ? endOftheYear_date : monthsForYear[j],
},
},
select: { actual_amount: true },
}));
}
for (let d of statements) {
// Calculate the total actual amount for the month
let total = 0;
d = await d
d.forEach((el) => {
total += el.actual_amount;
});
year.push(total);
}
graphDataOfYear = year;
// ```GRAPH CALCULATION FOR MONTHS```///////////////////////////
let startOfmonth = MOMENT().startOf('month');
let weeksForMonth = [];
let month = [];
// Create an array of dates representing the start of each week in the month
for (let index = 0; index <= 4; index++) {
const add1week = MOMENT(startOfmonth)
.add(index, 'weeks')
.format('YYYY-MM-DDTHH:mm:SS.000+00:00');
weeksForMonth.push(add1week);
}
console.log(weeksForMonth);
//-----------------------------------------------------------------
// Get the actual amount for each week
for (let i = 0; i < weeksForMonth.length; i++) {
let j = i + 1;
let d = await PRISMA.orders.findMany({
where: {
created_at: {
gte: weeksForMonth[i],
lte:
i === weeksForMonth.length - 1
? endOfMonth_date
: weeksForMonth[j],
},
},
select: { actual_amount: true },
});
// Calculate the total actual amount for the week
let total = 0;
d.forEach((el) => {
total += el.actual_amount;
});
month.push(total);
}
// Set the graph data to the calculated amounts
graphDataOfMonth = month;
// ```GRAPH CALCULATION FOR WEEKS```///////////////////////////////////////
let startOfWeek = MOMENT().startOf('week');
let daysForWeek = [];
let day = [];
// Create an array of dates representing the start of each day in the week
for (let index = 0; index <= 6; index++) {
const addDays = MOMENT(startOfWeek)
.add(index, 'days')
.format('YYYY-MM-DDTHH:mm:SS.000+00:00');
daysForWeek.push(addDays);
}
// Get the actual amount for each week
for (let i = 0; i < daysForWeek.length; i++) {
let j = i + 1;
let d = await PRISMA.orders.findMany({
where: {
created_at: {
gte: daysForWeek[i],
lte:
i === daysForWeek.length - 1
? endofweek_date
: daysForWeek[j],
},
},
select: { actual_amount: true },
});
// Calculate the total actual amount for the day
let total = 0;
d.forEach((el) => {
total += el.actual_amount;
});
day.push(total);
}
// Set the graph data to the calculated amounts
graphDataOfWeek = day;
//```GRAPH CALCULATION FOR DAYS````////////////////////////////////////////////////////////////
let startOfday = MOMENT().startOf('day');
let endOfday =
MOMENT().endOf('day').format('YYYY-MM-DD') + 'T00:00:00.000+00:00';
let hrsForDays = [];
let hrs = [];
// Create an array of dates representing the start of each hrs
for (let index = 0; index <= 24; index++) {
const addhrs = MOMENT(startOfday)
.add(index++, 'hours')
.format('YYYY-MM-DDTHH:mm:SS.000+00:00');
hrsForDays.push(addhrs);
}
// Get the actual amount for each hrs
for (let i = 0; i < hrsForDays.length; i++) {
let j = i + 1;
let d = await PRISMA.orders.findMany({
where: {
created_at: {
gte: hrsForDays[i],
lte: i === hrsForDays.length - 1 ? endOfday : hrsForDays[j],
},
},
select: { actual_amount: true },
});
// Calculate the total actual amount for the 2hrs
let total = 0;
d.forEach((el) => {
total += el.actual_amount;
});
hrs.push(total);
}
// Set the graph data to the calculated amounts
graphDataOfDays = hrs;
// console.log(graphDataOfDays)
console.log(graphDataOfYear)
console.log(graphDataOfMonth)
// console.log(graphDataOfWeek)
// filter_by Day Week Month Year CustomDate //////////////////////////////
if (location_id == '') {
if (filter_by === 'Day') {
query = {
created_at: {
gt: current_date,
},
ref: headerData?.ref,
};
} else if (filter_by === 'Week') {
// 7 days a week
graph_data = graphDataOfWeek;
query = {
created_at: {
gte: startofweek_date,
lte: endofweek_date,
},
ref: headerData?.ref,
};
} else if (filter_by === 'Month') {
// 4 weeks in a month
graph_data = graphDataOfMonth;
query = {
created_at: {
gte: startOfMonth_date,
lte: endOfMonth_date,
},
ref: headerData?.ref,
};
} else if (filter_by === 'Year') {
// 12 months_for_year in a year
graph_data = graphDataOfYear;
query = {
created_at: {
gte: startOfYear_date,
lte: endOftheYear_date,
},
ref: headerData?.ref,
};
} else if (filter_by === 'Custom') {
graph_data = [1, 2, 3, 4, 5, 7, 3, 12, 4, 2, 5, 6];
query = {
created_at: {
gte: custom_start_date,
lt: custom_end_date,
},
};
}
} else {
//if there is location id
if (filter_by === 'Day') {
//12 hrs in a day
graph_data = graphDataOfDays;
query = {
created_at: {
gt: current_date,
},
ref: headerData?.ref,
location_id: location_id,
};
} else if (filter_by === 'Week') {
// 7 days a week
graph_data = graphDataOfWeek;
query = {
created_at: {
gte: startofweek_date,
lte: endofweek_date,
},
ref: headerData?.ref,
location_id: location_id,
};
} else if (filter_by === 'Month') {
// 4 weeks in a month
graph_data = graphDataOfMonth;
query = {
created_at: {
gte: startOfMonth_date,
lte: endOfMonth_date,
},
ref: headerData?.ref,
location_id: location_id,
};
} else if (filter_by === 'Year') {
// 12 months_for_year in a year
graph_data = graphDataOfYear;
query = {
created_at: {
gte: startOfYear_date,
lte: endOftheYear_date,
},
ref: headerData?.ref,
location_id: location_id,
};
} else if (filter_by === 'Custom') {
graph_data = [1, 2, 3, 4, 5, 7, 3, 12, 4, 2, 5, 6];
query = {
created_at: {
gte: custom_start_date,
lt: custom_end_date,
},
ref: headerData?.ref,
location_id: location_id,
};
}
}
// ```Create new signup```; //----------------------------------------------
const new_sign_up = await PRISMA.customers.findMany({
where: {
ref: headerData?.ref,
},
orderBy: {
id: 'desc',
},
skip: 0,
take: 5,
});
// ```COUNT THE NUMBER OF ORDERS```; //----------------------------------------------
const orderCount = await PRISMA.orders.count({
where: query,
});
// ```NUMBER OF CUSTOMER DEVICES```; //----------------------------------------------
const ref = location_id == '' ? headerData?.ref : location_id;
let [android_devices, ios_devices, web_devices] = await Promise.all(
['ANDROID', 'IOS', 'WEBSITE'].map((channel) =>
PRISMA.customers.count({
where: {
channel,
ref,
},
})
)
);
// ```FIND TOTAL CUSTOMERS```; //----------------------------------------------
let total_customers = '';
if (location_id == '') {
total_customers = await PRISMA.customers.count();
} else {
total_customers = await PRISMA.customers.count({
where: {
ref: headerData?.ref,
location_id: location_id,
},
});
}
// ```FIND RECENT ORDER```; //----------------------------------------------
let recent_order = await PRISMA.orders.findMany({
take: 5,
where: query,
orderBy: {
ordered_date: 'desc',
},
include: {
customers: true,
},
});
//----------------------------------------------
res.send({
status: true,
status_code: query,
message: 'Success',
order_card: orderCount,
recent_order: recent_order,
billing_history: [],
device: [
{
android: android_devices,
ios: ios_devices,
website: web_devices,
},
],
new_sign_up: new_sign_up,
total_customers: total_customers,
Graph_data: graph_data,
});
}
} catch (error) {
const errors = throwErrors(
'Something went wrong!!!',
req,
res,
error,
'SERVER_ERROR'
);
res.status(200).send(error);
}
});
};