I’m facing an issue in finding a solution to this problem. The company wants to limit the orders to a certain quantity per day and carry over the excess orders to the next day. So far, I’ve managed to implement this logic. However, the problem arises when they want to change the date again if the following day exceeds a certain quantity. I’m struggling to achieve this. Currently, I limit the orders to 2, and by staying on the same date, I lose control over the orders for the next day unless I implement endless conditional statements calling functions to handle the following days. Can anyone provide some assistance?
Below are the functions providing the dates and also the code of the controller.
async function contarPedidosDelDia() {
return await Order.countDocuments({
order_date: {
$gte: getStartTimeOfDay(),
$lte: getEndTimeOfDay()
}
});
}
export const newOrder = async (req, res, next) => {
try {
// Llamar a la función para comenzar a controlar el límite de pedidos
let currentDate = getCurrentISODate()
const cantPedidosDelDia = await contarPedidosDelDia()
if(cantPedidosDelDia >= 2) {
currentDate = getDateTomorrowISO()
}
/* const user_orders = await Order.find({ user: req.user.id })
user_orders.forEach((user_order) => {
if (user_order.status === 'pendiente') {
throw new ErrorResponse('You already have an outstanding order.', 400)
}
}) */
const { quantity, promotion_id, payment_method, product_id, observation } = req.body
const file = req.file
let monto_descontado = 0
let total_bidones_descontado = 0
let total_bidones_sin_descuento = 0
let comprobante = ""
let user_balance = 0
// Verifica si el usuario existe
const user = await User.findById(req.user.id);
if (!user) {
throw new ErrorResponse('User not found', 404)
}
const product = await Product.findById(product_id);
if (!product) {
throw new ErrorResponse('No product found', 404);
}
if (!req.file) {
comprobante = 'No disponible'
}
if (req.file && payment_method === "Transferencia") {
comprobante = file.path
}
if (req.file && payment_method === "Efectivo") {
await cloudinary.uploader.destroy(req.file.filename);
comprobante = "No disponible"
}
if (user.balance > 0) {
user_balance = user.balance
}
if (promotion_id !== "") {
const promotion = await Promotion.findById(promotion_id)
if (!promotion) {
throw new ErrorResponse('Promotion not found', 404)
}
if (promotion.required_quantity > quantity) {
throw new ErrorResponse('Promotion is not applicable', 400)
}
//calculo del descuento aplicado a los bidones
const total_bidones_sin_descuento = product.price * quantity
monto_descontado = (total_bidones_sin_descuento * promotion.discounted_percentage) / 100;
total_bidones_descontado = total_bidones_sin_descuento - monto_descontado
const newOrder = new Order({
user: user.id,
product: product_id,
promotion: promotion_id,
quantity,
payment_method,
proof_of_payment_image: comprobante,
order_date: currentDate,
order_due_date: getDateNextMonthISO(),
observation,
total_amount: total_bidones_descontado - user_balance,
});
const savedOrder = await newOrder.save();
const populatedOrder = await Order.findById(savedOrder.id)
.populate('user', '-password')
.populate('product', '-img')
.populate('promotion', '-img')
res.status(201).json({
success: true,
populatedOrder,
discounted_quantity: user_balance
});
}
else {
total_bidones_sin_descuento = product.price * quantity
const newOrder = new Order({
user: user.id,
product: product_id,
promotion: null,
quantity,
payment_method,
proof_of_payment_image: comprobante,
order_date: currentDate,
order_due_date: getDateNextMonthISO(),
observation,
total_amount: total_bidones_sin_descuento - user_balance
});
const savedOrder = await newOrder.save();
const populatedOrder = await Order.findById(savedOrder.id)
.populate('user', '-password')
.populate('product')
res.status(201).json({
success: true,
populatedOrder,
discounted_quantity: user_balance
});
}
}
catch (error) {
next(error);
}
}
// DATE UTILS
// Función para obtener el inicio del día en el formato ISO 8601
export function getStartTimeOfDay() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0'); // Asegurar que tenga 2 dígitos
const day = String(now.getDate()).padStart(2, '0'); // Asegurar que tenga 2 dígitos
const startOfDay = `${year}-${month}-${day}T00:00:00.000Z`;
return startOfDay;
}
// Función para obtener el final del día en el formato ISO 8601
export function getEndTimeOfDay() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0'); // Asegurar que tenga 2 dígitos
const day = String(now.getDate()).padStart(2, '0'); // Asegurar que tenga 2 dígitos
const endOfDay = `${year}-${month}-${day}T23:59:59.999Z`;
return endOfDay;
}
// Función para obtener la fecha actual en formato ISO 8601
export function getCurrentISODate() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0'); // Asegurar que tenga 2 dígitos
const day = String(now.getDate()).padStart(2, '0'); // Asegurar que tenga 2 dígitos
const hours = String(now.getHours()).padStart(2, '0'); // Asegurar que tenga 2 dígitos
const minutes = String(now.getMinutes()).padStart(2, '0'); // Asegurar que tenga 2 dígitos
const seconds = String(now.getSeconds()).padStart(2, '0'); // Asegurar que tenga 2 dígitos
const milliseconds = String(now.getMilliseconds()).padStart(3, '0'); // Asegurar que tenga 3 dígitos
const currentISODate = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}Z`;
return currentISODate;
}
// Función para obtener la fecha actual más un día en formato ISO 8601
export function getDateTomorrowISO() {
const now = new Date();
const tomorrow = new Date(now);
tomorrow.setDate(now.getDate() + 1);
const year = tomorrow.getFullYear();
const month = String(tomorrow.getMonth() + 1).padStart(2, '0'); // Asegurar que tenga 2 dígitos
const day = String(tomorrow.getDate()).padStart(2, '0'); // Asegurar que tenga 2 dígitos
const tomorrowISODate = `${year}-${month}-${day}T00:00:00.000Z`;
return tomorrowISODate;
}
// Función para obtener la fecha actual más un mes en formato ISO 8601
export function getDateNextMonthISO() {
const now = new Date();
const nextMonth = new Date(now);
nextMonth.setMonth(now.getMonth() + 1);
const year = nextMonth.getFullYear();
const month = String(nextMonth.getMonth() + 1).padStart(2, '0'); // Asegurar que tenga 2 dígitos
const day = String(nextMonth.getDate()).padStart(2, '0'); // Asegurar que tenga 2 dígitos
const nextMonthISODate = `${year}-${month}-${day}T00:00:00.000Z`;
return nextMonthISODate;
}
help me pls, its my first job