diff --git a/config/S3Bucket.js b/config/S3Bucket.js index b0992e49438373741cf46687d3401870f0436cf0..4bc03e6a50e0706774f9bdbf2acb481cd0ae4f71 100644 --- a/config/S3Bucket.js +++ b/config/S3Bucket.js @@ -8,7 +8,7 @@ const uploadsDir = path.resolve(process.cwd(), "uploads"); if (!fs.existsSync(uploadsDir)) { try { fs.mkdirSync(uploadsDir, { recursive: true }); - console.log("āœ… Uploads directory created:", uploadsDir); + // console.log("āœ… Uploads directory created:", uploadsDir); } catch (error) { console.error("āŒ Error creating uploads directory:", error); // Fallback to temp directory if uploads directory creation fails @@ -16,7 +16,7 @@ if (!fs.existsSync(uploadsDir)) { if (!fs.existsSync(tempDir)) { fs.mkdirSync(tempDir, { recursive: true }); } - console.log("šŸ“ Using fallback temp directory:", tempDir); + // console.log("šŸ“ Using fallback temp directory:", tempDir); } } @@ -76,8 +76,8 @@ const generateUniqueFilename = (originalname, requestId = null) => { // upload to wordpress using rest api const uploadToWordpress = async (file) => { try { - console.log("šŸ“ File to upload:", file); - console.log("šŸ“‚ File path:", file.path); + // console.log("šŸ“ File to upload:", file); + // console.log("šŸ“‚ File path:", file.path); const WP_URL = process.env.WP_URL || 'https://media.phantasm.site'; const WP_USER = process.env.WP_USER || 'admin'; @@ -122,7 +122,7 @@ const uploadToWordpress = async (file) => { } ); - console.log("āœ… WordPress upload successful:", response.data); + // console.log("āœ… WordPress upload successful:", response.data); // Return WordPress media data return { @@ -148,8 +148,8 @@ const uploadToWordpress = async (file) => { // Uploads a file to AWS S3 bucket and returns the file URL const uploadToS3 = (file) => { // not uploading to s3 , uploading to wordpress using rest api - console.log("šŸ“ File to upload:", file); - console.log("šŸ“‚ File path:", file.path); + // console.log("šŸ“ File to upload:", file); + // console.log("šŸ“‚ File path:", file.path); return new Promise((resolve, reject) => { // Check if file exists before proceeding @@ -180,7 +180,7 @@ const uploadToS3 = (file) => { // Don't reject here, just log the warning } - console.log("āœ… AWS upload successful:", data.Location); + // console.log("āœ… AWS upload successful:", data.Location); resolve(data.Location); }); }); diff --git a/controllers/analytics.controller.js b/controllers/analytics.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..f4e81d400b458292cc9a441be307fcfefb16398d --- /dev/null +++ b/controllers/analytics.controller.js @@ -0,0 +1,193 @@ +const { + getStoreMetricsService, + getDriverMetricsService, + getProductMetricsService, + getCategoryBrandMetricsService, + getCustomerMetricsService, + getOrderMetricsService, + getAllAnalyticsMetricsService +} = require("../services/analytics.service"); + +// Get all analytics metrics +module.exports.getAllAnalyticsMetrics = async (req, res) => { + try { + const metrics = await getAllAnalyticsMetricsService(); + + res.status(200).json({ + status: true, + message: "Analytics metrics retrieved successfully", + data: { + stores: { + total: metrics.stores.total, + active: metrics.stores.active, + inactive: metrics.stores.inactive + }, + drivers: { + total: metrics.drivers.total, + onDuty: metrics.drivers.onDuty, + offDuty: metrics.drivers.offDuty + }, + products: { + total: metrics.products.total, + active: metrics.products.active, + inactive: metrics.products.inactive + }, + categories: metrics.categories, + brands: metrics.brands, + customers: { + total: metrics.customers.total, + active: metrics.customers.active, + newLast7Days: metrics.customers.newLast7Days + }, + orders: { + today: metrics.orders.today, + thisWeek: metrics.orders.thisWeek, + thisMonth: metrics.orders.thisMonth + } + } + }); + } catch (error) { + res.status(500).json({ + status: false, + message: "Error retrieving analytics metrics", + error: error.message + }); + } +}; + +// Get store metrics only +module.exports.getStoreMetrics = async (req, res) => { + try { + const metrics = await getStoreMetricsService(); + + res.status(200).json({ + status: true, + message: "Store metrics retrieved successfully", + data: { + total: metrics.total, + active: metrics.active, + inactive: metrics.inactive + } + }); + } catch (error) { + res.status(500).json({ + status: false, + message: "Error retrieving store metrics", + error: error.message + }); + } +}; + +// Get driver metrics only +module.exports.getDriverMetrics = async (req, res) => { + try { + const metrics = await getDriverMetricsService(); + + res.status(200).json({ + status: true, + message: "Driver metrics retrieved successfully", + data: { + total: metrics.total, + onDuty: metrics.onDuty, + offDuty: metrics.offDuty + } + }); + } catch (error) { + res.status(500).json({ + status: false, + message: "Error retrieving driver metrics", + error: error.message + }); + } +}; + +// Get product metrics only +module.exports.getProductMetrics = async (req, res) => { + try { + const metrics = await getProductMetricsService(); + + res.status(200).json({ + status: true, + message: "Product metrics retrieved successfully", + data: { + total: metrics.total, + active: metrics.active, + inactive: metrics.inactive + } + }); + } catch (error) { + res.status(500).json({ + status: false, + message: "Error retrieving product metrics", + error: error.message + }); + } +}; + +// Get category and brand metrics +module.exports.getCategoryBrandMetrics = async (req, res) => { + try { + const metrics = await getCategoryBrandMetricsService(); + + res.status(200).json({ + status: true, + message: "Category and brand metrics retrieved successfully", + data: { + categories: metrics.categories, + brands: metrics.brands + } + }); + } catch (error) { + res.status(500).json({ + status: false, + message: "Error retrieving category and brand metrics", + error: error.message + }); + } +}; + +// Get customer metrics only +module.exports.getCustomerMetrics = async (req, res) => { + try { + const metrics = await getCustomerMetricsService(); + + res.status(200).json({ + status: true, + message: "Customer metrics retrieved successfully", + data: { + total: metrics.total, + active: metrics.active, + newLast7Days: metrics.newLast7Days + } + }); + } catch (error) { + res.status(500).json({ + status: false, + message: "Error retrieving customer metrics", + error: error.message + }); + } +}; + +// Get order metrics only +module.exports.getOrderMetrics = async (req, res) => { + try { + const metrics = await getOrderMetricsService(); + + res.status(200).json({ + status: true, + message: "Order metrics retrieved successfully", + data: { + today: metrics.today, + thisWeek: metrics.thisWeek, + thisMonth: metrics.thisMonth + } + }); + } catch (error) { + res.status(500).json({ + status: false, + message: "Error retrieving order metrics", + error: error.message + }); + } +}; diff --git a/controllers/brand.controller.js b/controllers/brand.controller.js index f0067c2857e7700d66ee0f0af7e91468a0a55956..c6028c42404d810d7c4e8d98bf5f2e06a8078f3b 100644 --- a/controllers/brand.controller.js +++ b/controllers/brand.controller.js @@ -617,15 +617,15 @@ module.exports.getApprovedBrandsForStoreAdmin = async (req, res) => { // Override defaults with query parameters if provided if (isDeleted !== undefined) { whereClause.isDeleted = isDeleted === "true" || isDeleted === true; - console.log(`Filtering brands by isDeleted: ${whereClause.isDeleted}`); + // console.log(`Filtering brands by isDeleted: ${whereClause.isDeleted}`); } if (isBrandApproved !== undefined) { whereClause.isBrandApproved = isBrandApproved === "true" || isBrandApproved === true; - console.log( - `Filtering brands by isBrandApproved: ${whereClause.isBrandApproved}` - ); + // console.log( + // `Filtering brands by isBrandApproved: ${whereClause.isBrandApproved}` + // ); } // Set default values if not provided @@ -641,23 +641,18 @@ module.exports.getApprovedBrandsForStoreAdmin = async (req, res) => { switch (status.toLowerCase()) { case "active": whereClause.status = "active"; - console.log("Filtering brands by status: active"); break; case "inactive": whereClause.status = "inactive"; - console.log("Filtering brands by status: inactive"); break; case "approved": whereClause.status = "approved"; - console.log("Filtering brands by status: approved"); break; case "rejected": whereClause.status = "rejected"; - console.log("Filtering brands by status: rejected"); break; default: whereClause.status = "active"; // Default to active - console.log(`Invalid status value: ${status}. Using default: active`); break; } } else { diff --git a/controllers/cart.controller.js b/controllers/cart.controller.js index ade1143bc64ee9319ef3f2f414f0fdf38fce239e..7f928fd3501e2d258f3d78a56633ea8432969dcc 100644 --- a/controllers/cart.controller.js +++ b/controllers/cart.controller.js @@ -75,8 +75,6 @@ module.exports.addToCart = async (req, res) => { const { cartItems = [] } = req.body; const user = req.user; - console.log("userrrrr", user); - if (!cartItems || cartItems.length === 0) { await t.rollback(); return res.status(400).json({ @@ -412,7 +410,7 @@ module.exports.addToCart = async (req, res) => { if (isCart?.isFreeze) { const reduce = existingCartItem.quantity + parseInt(item.quantity); const newQuantity = Math.max(0, reduce); - console.log("Reducing quantity", reduce); + // console.log("Reducing quantity", reduce); // Reduce stock when cart is frozen const stockReduction = await reserveStockForCart( @@ -436,33 +434,33 @@ module.exports.addToCart = async (req, res) => { }); } - console.log( - "Updating existing cart item (frozen cart) - new quantity:", - newQuantity - ); + // console.log( + // "Updating existing cart item (frozen cart) - new quantity:", + // newQuantity + // ); await existingCartItem.update( { quantity: newQuantity }, { transaction: t } ); - console.log("Cart item updated successfully (frozen cart)"); + // console.log("Cart item updated successfully (frozen cart)"); } else { const newQuantity = existingCartItem.quantity + parseInt(item.quantity); - console.log( - "Updating existing cart item - new quantity:", - newQuantity - ); + // console.log( + // "Updating existing cart item - new quantity:", + // newQuantity + // ); await existingCartItem.update( { quantity: newQuantity }, { transaction: t } ); - console.log("Cart item updated successfully"); + // console.log("Cart item updated successfully"); } } else { // āœ… Item exists in different cart - move it to current cart - console.log( - `Moving item from cart ${existingCartItem.cart_id} to cart ${isCart.ID}` - ); + // console.log( + // `Moving item from cart ${existingCartItem.cart_id} to cart ${isCart.ID}` + // ); await existingCartItem.update( { cart_id: isCart.ID, @@ -470,7 +468,7 @@ module.exports.addToCart = async (req, res) => { }, { transaction: t } ); - console.log("Cart item moved and quantity updated successfully"); + // console.log("Cart item moved and quantity updated successfully"); } } else { const createData = { @@ -484,7 +482,7 @@ module.exports.addToCart = async (req, res) => { // console.log("Creating new cart item with data:", createData); await createOneCartItem(createData, { transaction: t }); - console.log("Cart item created successfully"); + // console.log("Cart item created successfully"); } } // Close the for loop @@ -528,9 +526,9 @@ module.exports.addToCart = async (req, res) => { } // Delete the old cart await cart.destroy({ transaction: t }); // āœ… Keep inside transaction - console.log( - `Removed duplicate cart ${cart.ID}, moved items to cart ${cartToKeep.ID}` - ); + // console.log( + // `Removed duplicate cart ${cart.ID}, moved items to cart ${cartToKeep.ID}` + // ); } } } else if (allActiveCarts.length === 1) { @@ -538,11 +536,11 @@ module.exports.addToCart = async (req, res) => { const cart = allActiveCarts[0]; if (!cart.cartItems || cart.cartItems.length === 0) { await cart.destroy({ transaction: t }); // āœ… Keep inside transaction - console.log(`Removed empty cart ${cart.ID}`); + // console.log(`Removed empty cart ${cart.ID}`); } } } catch (cleanupError) { - console.log("Cart cleanup error (non-critical):", cleanupError); + // console.log("Cart cleanup error (non-critical):", cleanupError); // Don't throw error, just log it } @@ -866,7 +864,6 @@ module.exports.clearCart = async (req, res) => { const t = await sequelize.transaction(); try { const user = req.user; - console.log("user id", user?.id); // Get all cart items before clearing const [cart, cartItems] = await Promise.all([ @@ -1034,9 +1031,9 @@ module.exports.viewCart = async (req, res) => { acc[key] = item; } else { // āœ… Duplicate found - consolidate quantities and move to primary cart - console.log( - `Consolidating duplicate: Product ${item.product_id}, Variant ${item.variation_id}` - ); + // console.log( + // `Consolidating duplicate: Product ${item.product_id}, Variant ${item.variation_id}` + // ); acc[key].quantity += item.quantity; // Move item to primary cart if it's in a different cart @@ -1211,7 +1208,7 @@ module.exports.finalCart = async (req, res) => { } // Check if cart is already frozen - console.log("Cart freeze status:", cart.isFreeze); + // console.log("Cart freeze status:", cart.isFreeze); // if (cart.isFreeze) { // console.log("Cart is already frozen, rolling back transaction"); // await t.rollback(); @@ -1315,7 +1312,7 @@ module.exports.finalCart = async (req, res) => { ); // Freeze the cart and store addresses - console.log("Freezing cart and storing addresses"); + // console.log("Freezing cart and storing addresses"); await updateCartService( { user_id: user.id }, { @@ -1324,7 +1321,7 @@ module.exports.finalCart = async (req, res) => { }, { transaction: t } ); - console.log("Cart frozen successfully"); + // console.log("Cart frozen successfully"); // Reduce stock for all items (since cart is now frozen) using cart's store_id const stockReduction = await reserveStockForCart( @@ -1397,9 +1394,9 @@ module.exports.finalCart = async (req, res) => { options: {}, }); - console.log("Committing finalCart transaction"); + // console.log("Committing finalCart transaction"); await t.commit(); - console.log("FinalCart transaction committed successfully"); + // console.log("FinalCart transaction committed successfully"); // Get updated cart with addresses (outside transaction since it's already committed) const updatedCart = await CART_MODEL.findOne({ diff --git a/controllers/category.controller.js b/controllers/category.controller.js index 187d096e12daad9a3926dcb3a8269c6321ae6d1f..3a0b427be93c6908cd6681d9f6ff697dfb89769c 100644 --- a/controllers/category.controller.js +++ b/controllers/category.controller.js @@ -749,8 +749,6 @@ module.exports.approveCategoryRequest = async (req, res) => { const { categoryId } = req.params; const { isApproved, notes = "" } = req.body; - console.log("isApproveddddd", isApproved); - // Check if user is super admin if (user.role !== "super-admin") { return res.status(403).json({ diff --git a/controllers/customer.controller.js b/controllers/customer.controller.js index 206975f2076188bce823c97c79293fde6ea72d04..e0075170dc5b098d67913935ec238a7d4251286e 100644 --- a/controllers/customer.controller.js +++ b/controllers/customer.controller.js @@ -438,13 +438,13 @@ module.exports.changeCustomerStatus = async (req, res) => { // Age Verification API module.exports.submitAgeVerification = async (req, res) => { try { - console.log("=== AGE VERIFICATION SUBMISSION ==="); - console.log("Validated data:", req.validatedData); - console.log( - "Files received:", - req.files ? Object.keys(req.files) : "No files" - ); - console.log("==================================="); + // console.log("=== AGE VERIFICATION SUBMISSION ==="); + // console.log("Validated data:", req.validatedData); + // console.log( + // "Files received:", + // req.files ? Object.keys(req.files) : "No files" + // ); + // console.log("==================================="); const { id } = req.params; const validatedData = req.validatedData; @@ -976,7 +976,6 @@ module.exports.resetPassword = async (req, res) => { message: "Your OTP has expired. Please request a new one to continue", }); } - console.log("new passwordddd", newPassword); // const hashedPassword = await bcrypt.hash(newPassword, 10); // console.log("hashedPasswordddd", hashedPassword); diff --git a/controllers/customerAccount.controller.js b/controllers/customerAccount.controller.js index 89213d2438b16772f8f0a1e71de478b31e4ffdf8..337ba9c08a6b3b73afdfc293c999e3bd23979c0d 100644 --- a/controllers/customerAccount.controller.js +++ b/controllers/customerAccount.controller.js @@ -62,7 +62,7 @@ module.exports.updateCustomerAddress = async (req, res) => { }; const fullAddress = buildAddressString(addressData); - console.log(`šŸ“ Geocoding ${type} address: ${fullAddress}`); + // console.log(`šŸ“ Geocoding ${type} address: ${fullAddress}`); // Get coordinates using geocoding service const coordinates = await geocodeAddress(fullAddress); @@ -70,7 +70,7 @@ module.exports.updateCustomerAddress = async (req, res) => { if (coordinates) { finalLatitude = coordinates.latitude.toString(); finalLongitude = coordinates.longitude.toString(); - console.log(`āœ… ${type} address geocoded: ${finalLatitude}, ${finalLongitude}`); + // console.log(`āœ… ${type} address geocoded: ${finalLatitude}, ${finalLongitude}`); } else { console.warn(`āš ļø Failed to geocode ${type} address, using default coordinates`); } @@ -399,7 +399,7 @@ module.exports.addCustomerAddress = async (req, res) => { }; const fullAddress = buildAddressString(addressData); - console.log(`šŸ“ Geocoding ${type} address: ${fullAddress}`); + // console.log(`šŸ“ Geocoding ${type} address: ${fullAddress}`); // Get coordinates using geocoding service const coordinates = await geocodeAddress(fullAddress); @@ -407,7 +407,7 @@ module.exports.addCustomerAddress = async (req, res) => { if (coordinates) { finalLatitude = coordinates.latitude.toString(); finalLongitude = coordinates.longitude.toString(); - console.log(`āœ… ${type} address geocoded: ${finalLatitude}, ${finalLongitude}`); + // console.log(`āœ… ${type} address geocoded: ${finalLatitude}, ${finalLongitude}`); } else { console.warn(`āš ļø Failed to geocode ${type} address, using default coordinates`); } @@ -440,7 +440,6 @@ module.exports.addCustomerAddress = async (req, res) => { }, } ); - console.log(`āœ… Removed default status from existing ${type} address ID: ${existingDefaultAddress.ID}`); } } diff --git a/controllers/customerAddress.controller.js b/controllers/customerAddress.controller.js index 0772e7832412e3b4e97536e9e81038990b932c24..0c4e047aedf29985e5e51eb54c24e646ef6e95ea 100644 --- a/controllers/customerAddress.controller.js +++ b/controllers/customerAddress.controller.js @@ -62,13 +62,13 @@ module.exports.createCustomerAddress = async (req, res) => { country, }); - console.log(`šŸ“ Geocoding address: ${fullAddress}`); + // console.log(`šŸ“ Geocoding address: ${fullAddress}`); const coordinates = await geocodeAddress(fullAddress); if (coordinates) { finalLatitude = coordinates.latitude; finalLongitude = coordinates.longitude; - console.log(`āœ… Address geocoded successfully: ${finalLatitude}, ${finalLongitude}`); + // console.log(`āœ… Address geocoded successfully: ${finalLatitude}, ${finalLongitude}`); } else { console.warn(`āš ļø Geocoding failed for address: ${fullAddress}`); // Use default coordinates if geocoding fails @@ -245,13 +245,13 @@ module.exports.updateCustomerAddress = async (req, res) => { }; const fullAddress = buildAddressString(addressData); - console.log(`šŸ“ Geocoding address for update: ${fullAddress}`); + // console.log(`šŸ“ Geocoding address for update: ${fullAddress}`); const coordinates = await geocodeAddress(fullAddress); if (coordinates) { finalLatitude = coordinates.latitude; finalLongitude = coordinates.longitude; - console.log(`āœ… Address geocoded successfully: ${finalLatitude}, ${finalLongitude}`); + // console.log(`āœ… Address geocoded successfully: ${finalLatitude}, ${finalLongitude}`); } else { console.warn(`āš ļø Geocoding failed for address: ${fullAddress}`); // Keep existing coordinates if geocoding fails diff --git a/controllers/driver.controller.js b/controllers/driver.controller.js index 77b110f35b1543b426dde7b3c65a9f610fa10183..1480be41a62079805d9ce3a784b6c3accac0c203 100644 --- a/controllers/driver.controller.js +++ b/controllers/driver.controller.js @@ -1005,13 +1005,6 @@ module.exports.updateDriverStatus = async (req, res) => { }); } - console.log("Driver object retrieved:", { - id: driver.ID, - email: driver.email, - userName: driver.userName, - status: driver.status, - }); - if (driver && driver?.status == status) { return res.status(400).json({ status: false, @@ -1049,9 +1042,6 @@ module.exports.updateDriverStatus = async (req, res) => { let driverEmail = driver?.email; let driverName = driver?.userName; - console.log("Driver email for notification:", driverEmail); - console.log("Driver name for notification:", driverName); - // Only emit email event if email is valid if (driverEmail && driverEmail.trim() !== "") { emitter.emit("driverStatusUpdatedMail", driverEmail, driverName, status); @@ -1531,8 +1521,6 @@ module.exports.driverLogin = async (req, res) => { message: "Invalid email or password", }); } - - console.log("driver?.status", driver?.status); // Check if driver is active if (driver.status == "pending_verification") { return res.status(401).json({ @@ -1907,8 +1895,6 @@ module.exports.startDriverShift = async (req, res) => { }); } - console.log("driver status", driver?.status); - // Check if driver is already on shift (using shiftStartTime to check if shift is active) if (driver.shiftStartTime && !driver.shiftEndTime) { return res.status(400).json({ @@ -2449,19 +2435,19 @@ module.exports.getDriverDailySummary = async (req, res) => { transactionId: transaction.id })); - console.log(`Processing ${timePeriods.length} transactions with time data out of ${todayTransactions.length} total transactions`); + // console.log(`Processing ${timePeriods.length} transactions with time data out of ${todayTransactions.length} total transactions`); // Log sample timestamp data for debugging if (timePeriods.length > 0) { - console.log('Sample timestamp data:', { - firstTransaction: { - orderId: timePeriods[0].id, - pickedAt: timePeriods[0].startTime, - deliveredAt: timePeriods[0].endTime, - pickedAtType: typeof timePeriods[0].startTime, - deliveredAtType: typeof timePeriods[0].endTime - } - }); + // console.log('Sample timestamp data:', { + // firstTransaction: { + // orderId: timePeriods[0].id, + // pickedAt: timePeriods[0].startTime, + // deliveredAt: timePeriods[0].endTime, + // pickedAtType: typeof timePeriods[0].startTime, + // deliveredAtType: typeof timePeriods[0].endTime + // } + // }); } // Calculate total time using utility function @@ -3682,7 +3668,6 @@ module.exports.confirmPickup = async (req, res) => { message: "Order not found", }); } - console.log("riverIddddd", driverId); // Check if driver is assigned and order is in pickup_pending status const driverAssignment = await getSingleAssignmentService({ @@ -3754,7 +3739,6 @@ module.exports.confirmPickedUp = async (req, res) => { } const driverId = user.id; - console.log("driverId", driverId); // Get all accepted assignments for this driver that are ready for pickup const driverAssignments = await getAssignmentsByDriverIdService({ @@ -3984,7 +3968,6 @@ module.exports.pickupOrder = async (req, res) => { // Start transaction transaction = await sequelize.transaction(); - console.log("šŸ”„ Transaction started for pickup order"); // Get all accepted orders for this driver that are in confirm_pickup status const driverAssignments = await getAssignmentsByDriverIdService({ @@ -4037,7 +4020,7 @@ module.exports.pickupOrder = async (req, res) => { order: [["assignedAt", "ASC"]], transaction, }); - console.log("driverAssignments", driverAssignments); + // console.log("driverAssignments", driverAssignments); if (!driverAssignments || driverAssignments.length === 0) { await transaction.rollback(); @@ -4118,7 +4101,6 @@ module.exports.pickupOrder = async (req, res) => { // Commit transaction await transaction.commit(); - console.log("āœ… Transaction committed successfully for pickup order"); // Update driver's last active time (after transaction commit) await updateDriverLastActive(driverId); @@ -4483,8 +4465,6 @@ module.exports.arrivedAtDelivery = async (req, res) => { const { user } = req; const driverId = user.id; - console.log(`🚚 Driver ${driverId} arrived at pickup location`); - // Get driver assignments with picked_up status const driverAssignments = await getAssignmentsByDriverIdService({ where: { @@ -4561,24 +4541,24 @@ module.exports.arrivedAtDelivery = async (req, res) => { data: null, }); } - console.log("driverAssignments", driverAssignments); + // console.log("driverAssignments", driverAssignments); // Convert to plain objects for easier access const plainAssignments = driverAssignments.map((assignment) => assignment.get({ plain: true }) ); - console.log("plainAssignments", plainAssignments); + // console.log("plainAssignments", plainAssignments); // Get orderId from the first assignment's order (from database, not req.body) const selectedOrder = plainAssignments[0]; // Always take the first available order const orderIdToUpdate = selectedOrder.order.ID; const assignmentIdToUpdate = selectedOrder.ID; - console.log(`šŸ“¦ Selected order ID from database: ${orderIdToUpdate}`); + // console.log(`šŸ“¦ Selected order ID from database: ${orderIdToUpdate}`); - console.log( - `šŸ“¦ Updating order ${orderIdToUpdate} status to arrived_at_pickup` - ); + // console.log( + // `šŸ“¦ Updating order ${orderIdToUpdate} status to arrived_at_pickup` + // ); // Update order status to arrived_at_pickup const updatedOrder = await updateOrderService(orderIdToUpdate, { @@ -4632,13 +4612,13 @@ module.exports.orderDelivered = async (req, res) => { customer_signature, } = req.body; - console.log( - `🚚 Driver ${driverId} attempting delivery with status: ${deliveryStatus}` - ); + // console.log( + // `🚚 Driver ${driverId} attempting delivery with status: ${deliveryStatus}` + // ); // Start transaction transaction = await sequelize.transaction(); - console.log("šŸ”„ Transaction started for order delivery"); + // Get driver assignments with picked_up status (orders ready for delivery) const driverAssignments = await getAssignmentsByDriverIdService({ @@ -4738,9 +4718,9 @@ module.exports.orderDelivered = async (req, res) => { const orderIdToUpdate = selectedOrder.order.ID; const assignmentIdToUpdate = selectedOrder.ID; - console.log( - `šŸ“¦ Processing delivery attempt for order ID: ${orderIdToUpdate} with status: ${deliveryStatus}` - ); + // console.log( + // `šŸ“¦ Processing delivery attempt for order ID: ${orderIdToUpdate} with status: ${deliveryStatus}` + // ); // Additional business logic validation if (deliveryStatus === "delivered") { @@ -4801,9 +4781,9 @@ module.exports.orderDelivered = async (req, res) => { deliveryInfo.failedAt = new Date().toISOString(); } - console.log( - `šŸ“¦ Updating order ${orderIdToUpdate} status based on delivery result: ${deliveryStatus}` - ); + // console.log( + // `šŸ“¦ Updating order ${orderIdToUpdate} status based on delivery result: ${deliveryStatus}` + // ); // Determine order status and assignment status based on delivery result let orderStatus, assignmentStatus, orderUpdateData; @@ -4892,9 +4872,9 @@ module.exports.orderDelivered = async (req, res) => { }); } - console.log( - `āœ… Transaction status updated to ${deliveryStatus} for order ${orderIdToUpdate}` - ); + // console.log( + // `āœ… Transaction status updated to ${deliveryStatus} for order ${orderIdToUpdate}` + // ); // Log activity const activityAction = @@ -5182,8 +5162,6 @@ module.exports.rejectOrder = async (req, res) => { }); } - console.log(`🚫 Driver ${user.id} rejected order ${orderId}`); - // Create activity log for order rejection const activityLogPayload = { action: "REJECT", @@ -6450,9 +6428,9 @@ module.exports.returnOrder = async (req, res) => { console.error("Failed to create transaction record for return"); // Don't fail the entire operation, just log the error } else { - console.log( - `āœ… Transaction record created for return: ${createdTransaction.id}` - ); + // console.log( + // `āœ… Transaction record created for return: ${createdTransaction.id}` + // ); } // Create activity log for return initiation diff --git a/controllers/order.controller.js b/controllers/order.controller.js index 865c6ecf254317155d3ddae91ae3cb531bbe8690..ecefdd29a7d82b4a633e9def4b27cdd20031915a 100644 --- a/controllers/order.controller.js +++ b/controllers/order.controller.js @@ -211,13 +211,10 @@ const findAvailableDrivers = async ( radiusKm = 2 ) => { try { - console.log( - `šŸ” Searching for drivers near store at ${storeLatitude}, ${storeLongitude} within ${radiusKm}km radius` - ); + // First, let's check total drivers in database const totalDrivers = await DRIVER_MODEL.count(); - console.log(`šŸ“Š Total drivers in database: ${totalDrivers}`); // Check drivers by each criteria const activeDrivers = await DRIVER_MODEL.count({ @@ -243,18 +240,6 @@ const findAvailableDrivers = async ( where: { currentLocation: { [Op.ne]: null } }, }); - console.log(`šŸ“Š Driver counts by criteria:`); - console.log(` - Total: ${totalDrivers}`); - console.log(` - Active: ${activeDrivers}`); - console.log(` - Status active: ${statusActiveDrivers}`); - console.log(` - Available: ${availableDriversCount}`); - console.log(` - Availability available: ${availabilityAvailableDrivers}`); - console.log(` - Online/Available status: ${onlineDrivers}`); - // console.log(` - Verified: ${verifiedDrivers}`); - // console.log(` - Background checked: ${backgroundCheckedDrivers}`); - // console.log(` - Documents verified: ${documentsVerifiedDrivers}`); - // console.log(` - Vehicle verified: ${vehicleVerifiedDrivers}`); - console.log(` - With location: ${driversWithLocation}`); // Get all available drivers const availableDrivers = await DRIVER_MODEL.findAll({ @@ -296,19 +281,14 @@ const findAvailableDrivers = async ( return []; } - console.log( - `āœ… Found ${availableDrivers.length} drivers meeting all criteria` - ); - console.log(`šŸ“ Now calculating distances for each driver...`); - // Calculate distance for each driver and filter by radius const driversWithDistance = availableDrivers .map((driver) => { const location = driver.currentLocation; if (!location || !location.coordinates) { - console.log( - `āš ļø Driver ${driver.ID} (${driver.firstName} ${driver.lastName}) has no location data` - ); + // console.log( + // `āš ļø Driver ${driver.ID} (${driver.firstName} ${driver.lastName}) has no location data` + // ); return null; } @@ -320,12 +300,6 @@ const findAvailableDrivers = async ( driverLongitude ); - console.log( - `šŸ“ Driver ${driver.ID} (${driver.firstName} ${ - driver.lastName - }): ${distance.toFixed(2)}km from store` - ); - return { ...driver.toJSON(), distance: distance, @@ -335,11 +309,11 @@ const findAvailableDrivers = async ( if (!driver) return false; const withinRadius = driver.distance <= radiusKm; if (!withinRadius) { - console.log( - `āš ļø Driver ${driver.ID} (${driver.firstName} ${ - driver.lastName - }) is too far: ${driver.distance.toFixed(2)}km > ${radiusKm}km` - ); + // console.log( + // `āš ļø Driver ${driver.ID} (${driver.firstName} ${ + // driver.lastName + // }) is too far: ${driver.distance.toFixed(2)}km > ${radiusKm}km` + // ); } return withinRadius; }) @@ -351,9 +325,6 @@ const findAvailableDrivers = async ( return a.distance - b.distance; }); - console.log( - `āœ… Found ${driversWithDistance.length} available drivers within ${radiusKm}km radius` - ); return driversWithDistance; } catch (error) { console.error("āŒ Error finding available drivers:", error); @@ -369,9 +340,6 @@ const findAvailableDrivers = async ( */ const assignOrderToDriver = async (orderId, storeId) => { try { - console.log( - `🚚 Starting order assignment for order ${orderId} from store ${storeId}` - ); // Get order details const order = await require("../models/orderModel").findByPk(orderId); @@ -385,9 +353,6 @@ const assignOrderToDriver = async (orderId, storeId) => { throw new Error("Store not found"); } - console.log(`šŸŖ Store details: ${store.storeName} (ID: ${store.ID})`); - console.log(`šŸ“ Store coordinates: ${store.latitude}, ${store.longitude}`); - if (!store.latitude || !store.longitude) { console.log(`āŒ Store ${store.ID} has no coordinates!`); throw new Error("Store coordinates not available"); @@ -404,9 +369,9 @@ const assignOrderToDriver = async (orderId, storeId) => { }); if (existingAssignment) { - console.log( - `āš ļø Order ${orderId} is already assigned to driver ${existingAssignment.driverId}` - ); + // console.log( + // `āš ļø Order ${orderId} is already assigned to driver ${existingAssignment.driverId}` + // ); return { success: false, message: "Order is already assigned to a driver", @@ -433,14 +398,14 @@ const assignOrderToDriver = async (orderId, storeId) => { // Select the best driver (first in sorted array) const selectedDriver = availableDrivers[0]; - console.log( - `āœ… Selected driver: ${selectedDriver.firstName} ${selectedDriver.lastName} (ID: ${selectedDriver.ID})` - ); - console.log( - `šŸ“ Distance: ${selectedDriver.distance.toFixed(2)}km, Rating: ${ - selectedDriver.averageRating - }` - ); + // console.log( + // `āœ… Selected driver: ${selectedDriver.firstName} ${selectedDriver.lastName} (ID: ${selectedDriver.ID})` + // ); + // console.log( + // `šŸ“ Distance: ${selectedDriver.distance.toFixed(2)}km, Rating: ${ + // selectedDriver.averageRating + // }` + // ); // Create assignment const assignment = await DRIVER_ORDER_ASSIGNMENT_MODEL.create({ @@ -487,9 +452,9 @@ const assignOrderToDriver = async (orderId, storeId) => { }, }); - console.log( - `šŸ“” Order assignment notification sent to driver ${selectedDriver.ID}` - ); + // console.log( + // `šŸ“” Order assignment notification sent to driver ${selectedDriver.ID}` + // ); } return { @@ -790,6 +755,7 @@ module.exports.getOrderById = async (req, res) => { completed: false, }, { status: "delivered", label: "Delivered", completed: false }, + { status: "return", label: "Returned", completed: false }, ]; // Mark completed statuses based on current order status @@ -804,6 +770,16 @@ module.exports.getOrderById = async (req, res) => { statusTimeline[i].timestamp = order.updatedAt || order.createdAt; } } + // If order is returned, it was not delivered – ensure delivered is not marked completed + if (order.order_status === "return") { + const deliveredIdx = statusTimeline.findIndex( + (item) => item.status === "delivered" + ); + if (deliveredIdx !== -1) { + statusTimeline[deliveredIdx].completed = false; + delete statusTimeline[deliveredIdx].timestamp; + } + } } // Get driver information if order is out for delivery or later @@ -990,8 +966,6 @@ module.exports.getUserOrders = async (req, res) => { const user = req.user; const { page = 1, limit = 10, status, filter } = req.query; - console.log("Request query params:", { page, limit, status, filter }); - const offset = (page - 1) * limit; const options = { limit: parseInt(limit), @@ -1469,8 +1443,6 @@ module.exports.getOrderByIdForSuperAdmin = async (req, res) => { try { const { orderId } = req.params; - console.log("Get order by ID for super admin:", { orderId }); - // Get order without store validation (super admin can access any order) const order = await getOrderByIdForSuperAdmin(orderId); @@ -2336,9 +2308,9 @@ module.exports.downloadShippingLabelPDF = async (req, res) => { "host" )}/uploads/labels/${barcodeFilename}`; - console.log( - `šŸ“± Generated barcode image for order ${order.ID}: ${barcodeText}` - ); + // console.log( + // `šŸ“± Generated barcode image for order ${order.ID}: ${barcodeText}` + // ); } catch (error) { console.error("Error generating barcode image:", error); // Continue without barcode image @@ -3352,8 +3324,8 @@ module.exports.getAvailableOrders = async (req, res) => { where: { ID: user?.id }, }); - console.log("user status", checkDriver?.status); - console.log("user driver avaialble", checkDriver.isAvailable); + // console.log("user status", checkDriver?.status); + // console.log("user driver avaialble", checkDriver.isAvailable); // Check if driver is active and available if ( !( @@ -4402,8 +4374,6 @@ module.exports.getOrderStatusCounts = async (req, res) => { const userRole = user?.role; const storeId = user?.storeId; - console.log("storeIddddd", storeId); - // Build where clause based on user role let whereClause = { store_id: storeId }; @@ -4750,7 +4720,7 @@ module.exports.createOrderForSuperAdmin = async (req, res) => { }) ); - console.log("cartItemsForCalculationnnnnnn",cartItemsForCalculation) + // console.log("cartItemsForCalculationnnnnnn",cartItemsForCalculation) // Calculate cart summary using the same function as ecommerce const cartSummary = await calculateCartSummary({ cartItems: cartItemsForCalculation, diff --git a/controllers/product.controller.js b/controllers/product.controller.js index 5a31b286e13f1cf0cdfeefb3449ad450bb027a70..be7985a772804cf9fa71e5648fccdf5dc90d04e3 100644 --- a/controllers/product.controller.js +++ b/controllers/product.controller.js @@ -219,7 +219,7 @@ module.exports.createProduct = async (req, res) => { message: "Product name is required", }); } - console.log("checnggggg"); + // console.log("checnggggg"); // Check if user is super admin or super admin employee (move this earlier) const isBySuperAdmin = isSuperAdminOrEmployee(user); @@ -258,7 +258,7 @@ module.exports.createProduct = async (req, res) => { }, transaction, }); - console.log("checkingggg 546544"); + // console.log("checkingggg 546544"); // Check if all provided category IDs exist and belong to this store const foundCategoryIds = storeCategories.map((cat) => cat.ID); const missingCategoryIds = categoryIds.filter( @@ -279,7 +279,7 @@ module.exports.createProduct = async (req, res) => { // Generate product SKU - using new function signature // Note: Final SKU will be set to product ID after creation const productSKU = generateSKU(0); // Temporary SKU, will be replaced - console.log("skuuuuuu"); + // console.log("skuuuuuu"); // Process uploaded files let finalProductImage = productImage || ""; @@ -342,7 +342,7 @@ module.exports.createProduct = async (req, res) => { transaction, }); } - console.log("gallery images"); + // console.log("gallery images"); // Create gallery images let allGalleryImages = []; @@ -369,7 +369,7 @@ module.exports.createProduct = async (req, res) => { transaction, }); } - console.log("after gallery images"); + // console.log("after gallery images"); // Handle variants based on product type if (isMultiVariant) { // Multi-variant product @@ -418,7 +418,7 @@ module.exports.createProduct = async (req, res) => { }); } } - console.log("barcodes"); + // console.log("barcodes"); let variantCounter = 1; // To build two-digit suffixes 01, 02, ... for (const variant of variants) { const { @@ -453,9 +453,9 @@ module.exports.createProduct = async (req, res) => { }); } - console.log("variants data starting"); + // console.log("variants data starting"); - console.log("variationTemplateIddddd", variationTemplateId); + // console.log("variationTemplateIddddd", variationTemplateId); // Step 3: Validate variation template and value IDs if (!variationTemplateId || !variationValueId) { @@ -499,7 +499,7 @@ module.exports.createProduct = async (req, res) => { message: `Variation value with ID ${variationValueId} not found or doesn't belong to template ${variationTemplateId}`, }); } - console.log("variation value"); + // console.log("variation value"); // Step 6: Create product variation record // First check if a product_variation record with the given productId and variation_template_id already exists let productVariation = await PRODUCT_VARIATION_MODEL.findOne({ @@ -521,9 +521,9 @@ module.exports.createProduct = async (req, res) => { }, { transaction } ); - console.log( - `Created new product variation record for product: ${productName}, template: ${variationTemplate.name}` - ); + // console.log( + // `Created new product variation record for product: ${productName}, template: ${variationTemplate.name}` + // ); } else { console.log( `Using existing product variation record for product: ${productName}, template: ${variationTemplate.name}` @@ -560,7 +560,7 @@ module.exports.createProduct = async (req, res) => { }; await VARIANT_MODEL.create(variantData, { transaction }); - console.log(`Created variant: ${itemName} for product: ${productName}`); + // console.log(`Created variant: ${itemName} for product: ${productName}`); variantCounter += 1; // Increment counter for next variant } } else { @@ -1592,7 +1592,7 @@ module.exports.updateBasicInfoOfProduct = async (req, res) => { } targetStoreId = user.storeId; - console.log("storeIddddd", targetStoreId); + // console.log("storeIddddd", targetStoreId); // Prevent store admin from specifying different storeId in body if (req.body.storeId && req.body.storeId !== user.storeId) { await safeRollback(transaction); @@ -1729,13 +1729,10 @@ module.exports.updateBasicInfoOfProduct = async (req, res) => { // Check if all provided category IDs exist and belong to this store const foundCategoryIds = storeCategories.map((cat) => cat.ID); - console.log("foundCategoryIdssssss", foundCategoryIds); const missingCategoryIds = categoryIds.filter( (id) => !foundCategoryIds.includes(id) ); - console.log("missingCategoryIdssssss", missingCategoryIds); - if (missingCategoryIds.length > 0) { await safeRollback(transaction); return res.status(400).json({ @@ -5781,7 +5778,7 @@ module.exports.getProductByStore = async (req, res) => { ], }); - console.log("otherStoresssss", otherStores); + // console.log("otherStoresssss", otherStores); const otherAvailableStores = otherStores.map((product) => { // Extract price information from variants @@ -5847,10 +5844,10 @@ module.exports.bulkCreateSingleProducts = async (req, res) => { const transaction = await sequelize.transaction(); try { - console.log("=== BULK CREATE SINGLE PRODUCTS ==="); - console.log("Request body:", req.body); - console.log("User:", req.user); - console.log("========================="); + // console.log("=== BULK CREATE SINGLE PRODUCTS ==="); + // console.log("Request body:", req.body); + // console.log("User:", req.user); + // console.log("========================="); const user = req.user; const { products = [] } = req.body; // Array of product objects @@ -6237,10 +6234,10 @@ module.exports.deleteProductByStoreAdmin = async (req, res) => { try { transaction = await sequelize.transaction(); - console.log("=== DELETE PRODUCT ==="); - console.log("Request params:", req.params); - console.log("User:", req.user); - console.log("========================="); + // console.log("=== DELETE PRODUCT ==="); + // console.log("Request params:", req.params); + // console.log("User:", req.user); + // console.log("========================="); const user = req.user; const { productId } = req.params; diff --git a/controllers/setting.controller.js b/controllers/setting.controller.js index 8d54e30e1d488170b22a149274c20677d7d4c3fd..d3c7c02979e3d7ff6ae6af3492cdc47dee0a12ff 100644 --- a/controllers/setting.controller.js +++ b/controllers/setting.controller.js @@ -134,10 +134,10 @@ const processBatchedActivityLogs = () => { // Single unified API to handle both settings and distribution modes module.exports.manageSettingsAndDistribution = async (req, res) => { const startTime = Date.now(); - console.log( - "šŸš€ Starting commission settings API at:", - new Date().toISOString() - ); + // console.log( + // "šŸš€ Starting commission settings API at:", + // new Date().toISOString() + // ); const transaction = await sequelize.transaction(); @@ -430,7 +430,7 @@ module.exports.manageSettingsAndDistribution = async (req, res) => { const endTime = Date.now(); const duration = endTime - startTime; - console.log(`āœ… Commission settings API completed in ${duration}ms`); + // console.log(`āœ… Commission settings API completed in ${duration}ms`); // Prepare response summary const settingsSummary = { @@ -512,14 +512,14 @@ module.exports.getSettingsAndDistribution = async (req, res) => { } // Execute queries in parallel with performance monitoring - console.log("šŸ” Fetching settings and distribution modes..."); + // console.log("šŸ” Fetching settings and distribution modes..."); const [settings, distributionModes] = await Promise.all([ getAllSettingsService(settingsQuery), getAllDistributionModesService(distributionModesQuery), ]); const queryTime = Date.now() - startTime; - console.log(`šŸ“Š Database queries completed in ${queryTime}ms`); + // console.log(`šŸ“Š Database queries completed in ${queryTime}ms`); // Format settings response using utility function const formattedSettings = formatSettings(settings); @@ -546,7 +546,7 @@ module.exports.getSettingsAndDistribution = async (req, res) => { }, []); const formatTime = Date.now() - startTime; - console.log(`šŸ”§ Data formatting completed in ${formatTime - queryTime}ms`); + // console.log(`šŸ”§ Data formatting completed in ${formatTime - queryTime}ms`); // Format distribution modes response using utility function const formattedDistributionModes = @@ -561,7 +561,7 @@ module.exports.getSettingsAndDistribution = async (req, res) => { ); const totalTime = Date.now() - startTime; - console.log(`āœ… GET commission-settings completed in ${totalTime}ms`); + // console.log(`āœ… GET commission-settings completed in ${totalTime}ms`); return res.status(200).json({ status: true, diff --git a/controllers/shiftTiming.controller.js b/controllers/shiftTiming.controller.js index a5c2923fadb8cc1b86e7bac0e05be53e968cfa2c..4c916cfd5a96f45254affc663ed9e4cb6fe68e2b 100644 --- a/controllers/shiftTiming.controller.js +++ b/controllers/shiftTiming.controller.js @@ -39,13 +39,13 @@ module.exports.createShiftTiming = async (req, res) => { }); // Log the created shift timing to verify shiftTime was generated - console.log("Created shift timing:", { - id: shiftTiming.ID, - shiftName: shiftTiming.shiftName, - shiftStartTime: shiftTiming.shiftStartTime, - shiftEndTime: shiftTiming.shiftEndTime, - shiftTime: shiftTiming.shiftTime, - }); + // console.log("Created shift timing:", { + // id: shiftTiming.ID, + // shiftName: shiftTiming.shiftName, + // shiftStartTime: shiftTiming.shiftStartTime, + // shiftEndTime: shiftTiming.shiftEndTime, + // shiftTime: shiftTiming.shiftTime, + // }); res.status(200).json({ status: true, diff --git a/controllers/stockAdjustment.controller.js b/controllers/stockAdjustment.controller.js index 6e3c403f74ee2b3f993e6e3017235c5728a6e7d7..01dd6cbd103fd3430e3de9b92a80c3d6826fbec1 100644 --- a/controllers/stockAdjustment.controller.js +++ b/controllers/stockAdjustment.controller.js @@ -40,9 +40,6 @@ module.exports.createStockAdjustment = async (req, res) => { // Get store_id from authenticated user token const store_id = req.user?.store_id || req.user?.storeId; - // Debug logging (remove in production) - console.log("Debug - Extracted store_id:", store_id); - console.log("Debug - Extracted userId:", userId); if (!store_id) { return res.status(400).json({ diff --git a/controllers/store.controller.js b/controllers/store.controller.js index 7ff5dad040a1e58031ec39775766d213945638a3..12c2df04fce1dbe929ab96e379da2c8537b036c8 100644 --- a/controllers/store.controller.js +++ b/controllers/store.controller.js @@ -111,7 +111,7 @@ module.exports.createStoreBasicDetails = async (req, res) => { // Ensure storeAdminId is included from section data storeAdminId: user?.id, }; - console.log("Store data to insert:", storeData); + // console.log("Store data to insert:", storeData); const newStore = await createStoreService(storeData); if (!newStore) { @@ -253,9 +253,7 @@ module.exports.updateStoreSection = async (req, res) => { // Add coordinates to update data updateData.latitude = coordinates.latitude; updateData.longitude = coordinates.longitude; - console.log( - `āœ… Store coordinates updated: ${coordinates.latitude}, ${coordinates.longitude}` - ); + } else { console.warn( "āš ļø Could not geocode address. Coordinates will remain unchanged." @@ -348,7 +346,7 @@ module.exports.updateStoreSection = async (req, res) => { existingUser.ID === existingStore.storeAdminId ) { // Same store admin, just updating email/password - console.log("Updating existing store admin:", existingStoreAdmin.ID); + // console.log("Updating existing store admin:", existingStoreAdmin.ID); // Update the existing user with new email and password await updateSingleUserWithHooksService( @@ -417,9 +415,7 @@ module.exports.updateStoreSection = async (req, res) => { // Verify that temporaryPassword was saved if (currentSection === "subscription" && sectionData.temporaryPassword) { - console.log("Checking if temporaryPassword was saved:"); - console.log("Original password:", sectionData.temporaryPassword); - console.log("Saved password:", updatedStore.temporaryPassword); + // console.log("Checking if temporaryPassword was saved:"); if (!updatedStore.temporaryPassword) { console.warn("WARNING: temporaryPassword was not saved to database!"); @@ -763,7 +759,7 @@ module.exports.getAllStores = async (req, res) => { where, }; - console.log("Final where:", JSON.stringify(where, null, 2)); + const { count, rows: storeData } = await getAllStoresAndCountsService( query @@ -1618,17 +1614,6 @@ module.exports.getStoreWithCategoriesAndProducts = async (req, res) => { }); } - // Log for debugging purposes - console.log( - `āœ… Found ${ - formattedProducts.length - } active products for store ${storeId}${ - categoryId ? ` in category ${categoryId}` : "" - } from ${storeCategoryIds.length} linked categories and ${ - categoryProductIds.length - } category products` - ); - return res.status(200).json({ status: true, message: "Products retrieved successfully", @@ -1642,6 +1627,7 @@ module.exports.getStoreWithCategoriesAndProducts = async (req, res) => { ERROR_RESPONSE(res, error); } }; + module.exports.getStoreCategoryCounts = async (req, res) => { try { const { storeId } = req.params; @@ -1652,17 +1638,19 @@ module.exports.getStoreCategoryCounts = async (req, res) => { SELECT c.ID AS categoryId, c.categoryName AS category, - COUNT(DISTINCT p.ID) AS productCount + COUNT(DISTINCT CASE + WHEN ps.productId IS NOT NULL + AND ps.storeId = ? + AND ps.isActive = true + AND p.status = 'active' + AND p.isDeleted = 0 + THEN p.ID + ELSE NULL + END) AS productCount FROM categories c LEFT JOIN product_category pc ON pc.category_id = c.ID - INNER JOIN products p - ON p.ID = pc.product_id - AND p.status = 'active' - AND p.isDeleted = 0 - INNER JOIN product_store ps - ON ps.productId = p.ID - AND ps.storeId = ? - AND ps.isActive = true + LEFT JOIN products p ON p.ID = pc.product_id + LEFT JOIN product_store ps ON ps.productId = p.ID WHERE c.isDeleted = false GROUP BY c.ID, c.categoryName ORDER BY c.categoryName ASC; @@ -1674,12 +1662,15 @@ module.exports.getStoreCategoryCounts = async (req, res) => { const totalCountResult = await sequelize.query( ` SELECT COUNT(DISTINCT p.ID) AS total - FROM products p - INNER JOIN product_store ps ON ps.productId = p.ID AND ps.storeId = ? AND ps.isActive = true - WHERE p.status = 'active' AND p.isDeleted = 0; +FROM products p +INNER JOIN product_category pc ON pc.product_id = p.ID +INNER JOIN categories c ON c.ID = pc.category_id AND c.isDeleted = false +INNER JOIN product_store ps ON ps.productId = p.ID AND ps.storeId = ? AND ps.isActive = true +WHERE p.status = 'active' AND p.isDeleted = 0; `, { replacements: [storeId], type: sequelize.QueryTypes.SELECT } ); + return res.status(200).json({ status: true, message: "Category counts fetched successfully", @@ -1735,11 +1726,6 @@ module.exports.getCategoriesByStore = async (req, res) => { }); } - // Log for debugging purposes - console.log( - `āœ… Found ${categoriesWithActiveProducts.length} categories with active products for store ${storeId}` - ); - // Data is already formatted by the utility function const formatted = categoriesWithActiveProducts; @@ -2205,7 +2191,7 @@ module.exports.superAdminUpdateStoreSection = async (req, res) => { existingUser.ID === existingStore.storeAdminId ) { // Same store admin, just updating email/password - console.log("Updating existing store admin:", existingStoreAdmin.ID); + // console.log("Updating existing store admin:", existingStoreAdmin.ID); // Update the existing user with new email and password await updateSingleUserWithHooksService( @@ -3027,9 +3013,9 @@ module.exports.bulkImportProductsToStore = async (req, res) => { }); } - console.log( - `āœ… Store-Category relationships updated: ${storeCategoryUpdates.length} updated, ${storeCategoryCreates.length} created` - ); + // console.log( + // `āœ… Store-Category relationships updated: ${storeCategoryUpdates.length} updated, ${storeCategoryCreates.length} created` + // ); } catch (storeCategoryError) { await transaction.rollback(); console.error("Store-category relationship error:", storeCategoryError); @@ -3057,9 +3043,9 @@ module.exports.bulkImportProductsToStore = async (req, res) => { transaction, } ); - console.log( - `āœ… Updated isImportedByStore flag for ${importedProductIds.length} products` - ); + // console.log( + // `āœ… Updated isImportedByStore flag for ${importedProductIds.length} products` + // ); } catch (updateError) { await transaction.rollback(); console.error("Error updating isImportedByStore flag:", updateError); @@ -3130,9 +3116,6 @@ module.exports.searchStores = async (req, res) => { ], }; - console.log(`Searching stores with term: "${search}"`); - console.log(`Where clause:`, JSON.stringify(whereClause, null, 2)); - // Debug: Check if there are any stores in the database at all const totalStores = await getAllStores({ attributes: [ @@ -3142,7 +3125,6 @@ module.exports.searchStores = async (req, res) => { "storeOwnerLastName", ], }); - console.log(`Total stores in database: ${totalStores.length}`); if (totalStores.length > 0) { // console.log(`Sample stores:`, totalStores.slice(0, 3).map(s => ({ // ID: s.ID, @@ -3177,15 +3159,13 @@ module.exports.searchStores = async (req, res) => { ], order: [["storeName", "ASC"]], }); - - console.log(`Found ${stores.length} stores`); if (stores.length > 0) { - console.log(`First store:`, { - ID: stores[0].ID, - storeName: stores[0].storeName, - storeOwnerFirstName: stores[0].storeOwnerFirstName, - storeOwnerLastName: stores[0].storeOwnerLastName, - }); + // console.log(`First store:`, { + // ID: stores[0].ID, + // storeName: stores[0].storeName, + // storeOwnerFirstName: stores[0].storeOwnerFirstName, + // storeOwnerLastName: stores[0].storeOwnerLastName, + // }); } // Format the response @@ -3301,7 +3281,7 @@ module.exports.getStorePayoutOverview = async (req, res) => { attributes: ["id"], }); - console.log("Revenue transactions:", revenueTransactions); + // console.log("Revenue transactions:", revenueTransactions); // Query for store payouts (debit amounts from transaction_payments) const storePayouts = await getAllTransactionPaymentDetailsService({ where: { @@ -3321,7 +3301,7 @@ module.exports.getStorePayoutOverview = async (req, res) => { order: [["paid_on", "DESC"]], }); - console.log("Store payouts:", storePayouts); + // console.log("Store payouts:", storePayouts); // Calculate summary statistics // const totalRevenue = revenueTransactions.reduce((sum, transaction) => { @@ -3332,17 +3312,17 @@ module.exports.getStorePayoutOverview = async (req, res) => { return sum + parseFloat(transaction.store_profit || 0); }, 0); - console.log("Total store profit:", totalStoreProfit); + // console.log("Total store profit:", totalStoreProfit); const totalPayoutAmount = storePayouts.reduce((sum, payout) => { return sum + parseFloat(payout.amount || 0); }, 0); - console.log("Total payout amount:", totalPayoutAmount); + // console.log("Total payout amount:", totalPayoutAmount); const totalPendingPayout = totalStoreProfit - totalPayoutAmount; - console.log("Total pending payout:", totalPendingPayout); + // console.log("Total pending payout:", totalPendingPayout); // Pagination info const { getPagination } = require("../utils/pagination"); @@ -3352,7 +3332,7 @@ module.exports.getStorePayoutOverview = async (req, res) => { totalRevenueTransactions.length ); - console.log("Pagination:", pagination); + // console.log("Pagination:", pagination); return res.status(200).json({ status: true, @@ -3377,7 +3357,7 @@ module.exports.getStorePayoutOverview = async (req, res) => { module.exports.getStorePayoutOverviewSuperAdmin = async (req, res) => { try { const { storeId } = req.params; - console.log("inside getStorePayoutOverviewSuperAdmin"); + // console.log("inside getStorePayoutOverviewSuperAdmin"); if (!storeId) { return res.status(400).json({ @@ -3554,10 +3534,10 @@ module.exports.getStorePayoutOverviewSuperAdmin = async (req, res) => { }, }; - console.log( - "šŸ“Š Store payout overview (Super Admin) calculated:", - payoutOverviewData - ); + // console.log( + // "šŸ“Š Store payout overview (Super Admin) calculated:", + // payoutOverviewData + // ); return res.status(200).json({ status: true, @@ -3940,7 +3920,7 @@ module.exports.getStoreOverview = async (req, res) => { }, }; - console.log("šŸ“Š Store overview calculated:", overviewData); + // console.log("šŸ“Š Store overview calculated:", overviewData); return res.status(200).json({ status: true, @@ -4233,7 +4213,7 @@ module.exports.getMonthlyEarningsSuperAdmin = async (req, res) => { // avgPerTrip: parseFloat(overallAvgPerTrip.toFixed(2)), // completionRate: "96.8%", // This could be calculated based on delivered vs total orders // }, - console.log("šŸ“Š Monthly earnings (super admin) calculated:", formattedData); + // console.log("šŸ“Š Monthly earnings (super admin) calculated:", formattedData); return res.status(200).json({ status: true, message: "Monthly earnings retrieved successfully", @@ -4326,7 +4306,7 @@ module.exports.updateStoreCreditLimits = async (req, res) => { return res.status(200).json({ status: true, - message: "Store credit limits updated successfully" + message: "Store credit limits updated successfully", }); } catch (error) { console.error("Update store credit limits error:", error); diff --git a/controllers/tax.controller.js b/controllers/tax.controller.js index 905bf4aa24dbc3bbc0b29d2487631905e8f258cc..938551aa626c0f400af22a3095324e37a34ba05f 100644 --- a/controllers/tax.controller.js +++ b/controllers/tax.controller.js @@ -296,8 +296,6 @@ module.exports.deleteTax = async (req, res) => { const { id } = req.params; const taxId = parseInt(id); - console.log("Deleting tax with ID:", taxId); - // Check if tax exists const tax = await getTaxByIdService(taxId); if (!tax) { @@ -323,8 +321,6 @@ module.exports.deleteTax = async (req, res) => { transaction }); - console.log(`Found ${taxesToUpdate} taxes and ${productsToUpdate} products to update`); - // 1. Update other taxes that reference this taxId (set to null) if (taxesToUpdate > 0) { await TAX_MODEL.update( @@ -334,7 +330,7 @@ module.exports.deleteTax = async (req, res) => { transaction } ); - console.log(`Updated ${taxesToUpdate} taxes to remove taxId reference`); + } // 2. Update products that use this tax category (set locationTaxType to null) @@ -346,7 +342,7 @@ module.exports.deleteTax = async (req, res) => { transaction } ); - console.log(`Updated ${productsToUpdate} products to remove locationTaxType reference`); + } // 3. Delete the tax record diff --git a/controllers/user.controller.js b/controllers/user.controller.js index 864aa3074707e3d607b5eadd94389c19523f1bfd..16c7132d203741eabab0f2a380806c6e314f52fb 100644 --- a/controllers/user.controller.js +++ b/controllers/user.controller.js @@ -1393,14 +1393,8 @@ module.exports.changeUserStatus = async (req, res) => { }, }); } - - console.log("Current user status:", existingUser.status); - console.log("Updating to status:", status); - const updatedUser = await updateUserService(id, { status }); - console.log("Update result:", updatedUser); - // Return user without password const { password, ...userWithoutPassword } = updatedUser.toJSON(); diff --git a/index.js b/index.js index 6d956211de3f68bc7af982dbddcd130bdb0971ee..eb2f6974721cc43b7f92b7ef707394e61a99b3eb 100644 --- a/index.js +++ b/index.js @@ -42,6 +42,7 @@ const stockAdjustmentRoutes = require("./routes/stockAdjustment.routes"); const productStockRoutes = require("./routes/productStock.routes"); const activityLogRoutes = require("./routes/activityLog.routes"); const settingRoutes = require("./routes/setting.routes"); +const analyticsRoutes = require("./routes/analytics.routes"); const DRIVER_MODEL = require("./models/driver.model"); const STRIKE_MODEL = require("./models/strike.model"); const MAIN_CATEGORY_MODEL = require("./models/mainCategories.model"); @@ -174,6 +175,7 @@ app.use("/api/product-stock", productStockRoutes); app.use("/api/activity-logs", activityLogRoutes); app.use("/api/firebase", firebaseRouter); app.use("/api/commission-settings", settingRoutes); +app.use("/api/analytics", analyticsRoutes); /********** To sync the db *********/ async function initializeDatabase() { diff --git a/routes/analytics.routes.js b/routes/analytics.routes.js new file mode 100644 index 0000000000000000000000000000000000000000..2ead96bb131fb1e45ac81d8ed14b4878a4b792d1 --- /dev/null +++ b/routes/analytics.routes.js @@ -0,0 +1,67 @@ +const express = require("express"); + +const router = express.Router(); + +const analyticsController = require("../controllers/analytics.controller"); +const { + authentication, + requirePermission, +} = require("../middleware/authMiddleware"); + +// Get all analytics metrics +router.get( + "/metrics", + authentication, + requirePermission("analytics.read"), + analyticsController.getAllAnalyticsMetrics +); + +// Get store metrics only +router.get( + "/stores-metrics", + authentication, + // requirePermission("analytics.read"), + analyticsController.getStoreMetrics +); + +// Get driver metrics only +router.get( + "/drivers", + authentication, + // requirePermission("analytics.read"), + analyticsController.getDriverMetrics +); + +// Get product metrics only +router.get( + "/products", + authentication, + // requirePermission("analytics.read"), + analyticsController.getProductMetrics +); + +// Get category and brand metrics +router.get( + "/categories-brands", + authentication, + // requirePermission("analytics.read"), + analyticsController.getCategoryBrandMetrics +); + +// Get customer metrics only +router.get( + "/customers", + authentication, + // requirePermission("analytics.read"), + analyticsController.getCustomerMetrics +); + +// Get order metrics only +router.get( + "/orders", + authentication, + // requirePermission("analytics.read"), + analyticsController.getOrderMetrics +); + +module.exports = router; diff --git a/scripts/checkStoreCoordinates.js b/scripts/checkStoreCoordinates.js index 0bca023be1e2d4cfaebefb3389f2aaf17eaa6f4c..69fd0fda9101e8629e9004596b321748604479e0 100644 --- a/scripts/checkStoreCoordinates.js +++ b/scripts/checkStoreCoordinates.js @@ -12,7 +12,7 @@ const checkStoreCoordinates = async () => { // Get total count of stores const totalStores = await STORE_MODEL.count(); - console.log(`šŸ“Š Total stores: ${totalStores}`); + // console.log(`šŸ“Š Total stores: ${totalStores}`); // Get stores with coordinates const storesWithCoordinates = await STORE_MODEL.count({ @@ -62,18 +62,18 @@ const checkStoreCoordinates = async () => { } }); - console.log("šŸ“ˆ COORDINATES STATUS:"); - console.log(`āœ… Stores with coordinates: ${storesWithCoordinates}`); - console.log(`āŒ Stores without coordinates: ${storesWithoutCoordinates}`); - console.log(`āš ļø Stores with partial coordinates: ${storesWithPartialCoordinates}`); + // console.log("šŸ“ˆ COORDINATES STATUS:"); + // console.log(`āœ… Stores with coordinates: ${storesWithCoordinates}`); + // console.log(`āŒ Stores without coordinates: ${storesWithoutCoordinates}`); + // console.log(`āš ļø Stores with partial coordinates: ${storesWithPartialCoordinates}`); // Show percentage const percentageWithCoordinates = ((storesWithCoordinates / totalStores) * 100).toFixed(1); - console.log(`šŸ“Š Percentage with coordinates: ${percentageWithCoordinates}%`); + // console.log(`šŸ“Š Percentage with coordinates: ${percentageWithCoordinates}%`); // Show stores that need coordinates if (storesWithoutCoordinates > 0) { - console.log("\nšŸ“ STORES NEEDING COORDINATES:"); + // console.log("\nšŸ“ STORES NEEDING COORDINATES:"); const storesNeedingCoordinates = await STORE_MODEL.findAll({ where: { @@ -99,14 +99,14 @@ const checkStoreCoordinates = async () => { storesNeedingCoordinates.forEach((store, index) => { const address = [store.addressLine1, store.city, store.state].filter(Boolean).join(', '); - console.log(`${index + 1}. ${store.storeName} (${store.uniqueStoreId})`); - console.log(` Address: ${address || 'No address data'}`); - console.log(` Current: lat=${store.latitude}, lng=${store.longitude}`); - console.log(''); + // console.log(`${index + 1}. ${store.storeName} (${store.uniqueStoreId})`); + // console.log(` Address: ${address || 'No address data'}`); + // console.log(` Current: lat=${store.latitude}, lng=${store.longitude}`); + // console.log(''); }); } - console.log("=".repeat(50)); + // console.log("=".repeat(50)); } catch (error) { console.error("āŒ Script error:", error); diff --git a/services/analytics.service.js b/services/analytics.service.js new file mode 100644 index 0000000000000000000000000000000000000000..b71cab0293c3f42bba792971cb61ad7f65959453 --- /dev/null +++ b/services/analytics.service.js @@ -0,0 +1,204 @@ +const { Op } = require("sequelize"); +const { + STORE_MODEL, + DRIVER_MODEL, + PRODUCT_MODEL, + CATEGORY_MODEL, + BRAND_MODEL, + CUSTOMER_MODEL, + ORDER_MODEL +} = require("../models/associations"); + +// Get store metrics +const getStoreMetricsService = async () => { + try { + const totalStores = await STORE_MODEL.count(); + const activeStores = await STORE_MODEL.count({ + where: { status: "active" } + }); + const inactiveStores = totalStores - activeStores; + + return { + total: totalStores, + active: activeStores, + inactive: inactiveStores + }; + } catch (error) { + throw new Error(`Error getting store metrics: ${error.message}`); + } +}; + +// Get driver metrics +const getDriverMetricsService = async () => { + try { + const totalDrivers = await DRIVER_MODEL.count(); + const onDutyDrivers = await DRIVER_MODEL.count({ + where: { + currentStatus: "online", + isAvailable: true + } + }); + const offDutyDrivers = totalDrivers - onDutyDrivers; + + return { + total: totalDrivers, + onDuty: onDutyDrivers, + offDuty: offDutyDrivers + }; + } catch (error) { + throw new Error(`Error getting driver metrics: ${error.message}`); + } +}; + +// Get product metrics +const getProductMetricsService = async () => { + try { + const totalProducts = await PRODUCT_MODEL.count(); + const activeProducts = await PRODUCT_MODEL.count({ + where: { status: "active" } + }); + const inactiveProducts = totalProducts - activeProducts; + + return { + total: totalProducts, + active: activeProducts, + inactive: inactiveProducts + }; + } catch (error) { + throw new Error(`Error getting product metrics: ${error.message}`); + } +}; + +// Get category and brand metrics +const getCategoryBrandMetricsService = async () => { + try { + const totalCategories = await CATEGORY_MODEL.count(); + const totalBrands = await BRAND_MODEL.count(); + + return { + categories: totalCategories, + brands: totalBrands + }; + } catch (error) { + throw new Error(`Error getting category and brand metrics: ${error.message}`); + } +}; + +// Get customer metrics +const getCustomerMetricsService = async () => { + try { + const totalCustomers = await CUSTOMER_MODEL.count(); + const activeCustomers = await CUSTOMER_MODEL.count({ + where: { status: "active" } + }); + + // New customers in last 7 days + const sevenDaysAgo = new Date(); + sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7); + + const newCustomersLast7Days = await CUSTOMER_MODEL.count({ + where: { + createdAt: { + [Op.gte]: sevenDaysAgo + } + } + }); + + return { + total: totalCustomers, + active: activeCustomers, + newLast7Days: newCustomersLast7Days + }; + } catch (error) { + throw new Error(`Error getting customer metrics: ${error.message}`); + } +}; + +// Get order metrics +const getOrderMetricsService = async () => { + try { + const today = new Date(); + today.setHours(0, 0, 0, 0); + + const weekAgo = new Date(); + weekAgo.setDate(weekAgo.getDate() - 7); + + const monthAgo = new Date(); + monthAgo.setMonth(monthAgo.getMonth() - 1); + + const ordersToday = await ORDER_MODEL.count({ + where: { + createdAt: { + [Op.gte]: today + } + } + }); + + const ordersThisWeek = await ORDER_MODEL.count({ + where: { + createdAt: { + [Op.gte]: weekAgo + } + } + }); + + const ordersThisMonth = await ORDER_MODEL.count({ + where: { + createdAt: { + [Op.gte]: monthAgo + } + } + }); + + return { + today: ordersToday, + thisWeek: ordersThisWeek, + thisMonth: ordersThisMonth + }; + } catch (error) { + throw new Error(`Error getting order metrics: ${error.message}`); + } +}; + +// Get all analytics metrics +const getAllAnalyticsMetricsService = async () => { + try { + const [ + storeMetrics, + driverMetrics, + productMetrics, + categoryBrandMetrics, + customerMetrics, + orderMetrics + ] = await Promise.all([ + getStoreMetricsService(), + getDriverMetricsService(), + getProductMetricsService(), + getCategoryBrandMetricsService(), + getCustomerMetricsService(), + getOrderMetricsService() + ]); + + return { + stores: storeMetrics, + drivers: driverMetrics, + products: productMetrics, + categories: categoryBrandMetrics.categories, + brands: categoryBrandMetrics.brands, + customers: customerMetrics, + orders: orderMetrics + }; + } catch (error) { + throw new Error(`Error getting all analytics metrics: ${error.message}`); + } +}; + +module.exports = { + getStoreMetricsService, + getDriverMetricsService, + getProductMetricsService, + getCategoryBrandMetricsService, + getCustomerMetricsService, + getOrderMetricsService, + getAllAnalyticsMetricsService +}; diff --git a/services/sellLine.service.js b/services/sellLine.service.js index ee1ab1825caae15c857f3de758f5410ec49044dd..b23451428f2a6b257d8529820272e53784b3f301 100644 --- a/services/sellLine.service.js +++ b/services/sellLine.service.js @@ -39,3 +39,4 @@ module.exports.updateSellLineService = async (sellLineId, updateData, options = throw new Error(`Error updating sell line: ${error.message}`); } }; + diff --git a/utils/cartCalculations.js b/utils/cartCalculations.js index a7c60c13a320a0bc04501e5428c9f33b9874b584..87acf0e51893d75b5e48524401d7b6344767ce74 100644 --- a/utils/cartCalculations.js +++ b/utils/cartCalculations.js @@ -177,8 +177,8 @@ const calculateDynamicItemTax = async ({ itemTotal, variant, }) => { - console.log("itemTotal", itemTotal); - console.log("productttt", product?.ml); + // console.log("itemTotal", itemTotal); + // console.log("productttt", product?.ml); try { let taxAmount = 0; @@ -227,8 +227,8 @@ const calculateDynamicItemTax = async ({ const { value, taxType } = taxRateRecord; taxRate = parseFloat(value) || 0; - console.log("taxRate", taxRate, "taxType", taxType); - console.log("product.mlllll", product.ml); + // console.log("taxRate", taxRate, "taxType", taxType); + // console.log("product.mlllll", product.ml); // Get the tax type (inclusive/exclusive) from the product const productTaxType = product?.taxType || "exclusive"; @@ -240,7 +240,7 @@ const calculateDynamicItemTax = async ({ // Tax based on milliliters if (product.ml && product.ml > 0) { taxAmount = parseInt(product.ml) * parseFloat(taxRate); - console.log("ml tax amount", taxAmount); + // console.log("ml tax amount", taxAmount); } break; @@ -280,7 +280,7 @@ const calculateDynamicItemTax = async ({ break; } } - console.log("taxAmounttttt", taxAmount); + // console.log("taxAmounttttt", taxAmount); return { itemTax: parseFloat(taxAmount.toFixed(2)), taxRate: taxRate, @@ -312,7 +312,7 @@ const calculateItemTax = async ({ quantity, customerState = null, }) => { - console.log("tax calculation is testingggg", product); + // console.log("tax calculation is testingggg", product); // If customer state is provided, use dynamic tax calculation if (customerState && product?.locationTaxType) { return await calculateDynamicItemTax({ @@ -350,16 +350,16 @@ const calculateItemTax = async ({ // Calculate shipping charges based on flat rate or percentage const calculateShippingCharges = (chargeRecord, cartCalculations) => { - console.log("🚚 calculateShippingCharges called with:", { - chargeRecord: chargeRecord - ? { - id: chargeRecord.ID, - valueType: chargeRecord.valueType, - value: chargeRecord.value, - } - : null, - cartSubtotal: cartCalculations?.subtotal, - }); + // console.log("🚚 calculateShippingCharges called with:", { + // chargeRecord: chargeRecord + // ? { + // id: chargeRecord.ID, + // valueType: chargeRecord.valueType, + // value: chargeRecord.value, + // } + // : null, + // cartSubtotal: cartCalculations?.subtotal, + // }); if (!chargeRecord) { console.log("āŒ No charge record provided for shipping charges"); @@ -385,16 +385,16 @@ const calculateShippingCharges = (chargeRecord, cartCalculations) => { // Calculate platform fee based on flat rate or percentage const calculatePlatformFee = (chargeRecord, cartCalculations) => { - console.log("šŸ¢ calculatePlatformFee called with:", { - chargeRecord: chargeRecord - ? { - id: chargeRecord.ID, - valueType: chargeRecord.valueType, - value: chargeRecord.value, - } - : null, - cartSubtotal: cartCalculations?.subtotal, - }); + // console.log("šŸ¢ calculatePlatformFee called with:", { + // chargeRecord: chargeRecord + // ? { + // id: chargeRecord.ID, + // valueType: chargeRecord.valueType, + // value: chargeRecord.value, + // } + // : null, + // cartSubtotal: cartCalculations?.subtotal, + // }); if (!chargeRecord) { console.log("āŒ No charge record provided for platform fee"); @@ -474,24 +474,24 @@ const calculateOtherCharges = async ({ tipAmount, }) => { try { - console.log( - "šŸ”§ calculateOtherCharges - Starting calculation with params:", - { - cartCalculations, - estimatedDistance, - estimatedDuration, - } - ); + // console.log( + // "šŸ”§ calculateOtherCharges - Starting calculation with params:", + // { + // cartCalculations, + // estimatedDistance, + // estimatedDuration, + // } + // ); // Get all active charge settings from database const allOtherCharges = await getAllSettingsService({ where: { isActive: true }, }); - console.log("šŸ“Š allOtherCharges from database:", allOtherCharges); - console.log( - "šŸ“Š Number of active charge records found:", - allOtherCharges?.length || 0 - ); + // console.log("šŸ“Š allOtherCharges from database:", allOtherCharges); + // console.log( + // "šŸ“Š Number of active charge records found:", + // allOtherCharges?.length || 0 + // ); // Initialize consolidated results object const consolidatedCharges = { @@ -510,24 +510,24 @@ const calculateOtherCharges = async ({ let totalSurcharges = 0; // Process each charge record using for loop - console.log("šŸ”„ Processing charge records..."); + // console.log("šŸ”„ Processing charge records..."); for (const chargeRecord of allOtherCharges) { - console.log(`\nšŸ” Processing charge record:`, { - id: chargeRecord.ID, - type: chargeRecord.type, - subType: chargeRecord.subType, - valueType: chargeRecord.valueType, - value: chargeRecord.value, - isActive: chargeRecord.isActive, - isSurcharge: chargeRecord.isSurcharge, - description: chargeRecord.description, - }); + // console.log(`\nšŸ” Processing charge record:`, { + // id: chargeRecord.ID, + // type: chargeRecord.type, + // subType: chargeRecord.subType, + // valueType: chargeRecord.valueType, + // value: chargeRecord.value, + // isActive: chargeRecord.isActive, + // isSurcharge: chargeRecord.isSurcharge, + // description: chargeRecord.description, + // }); let calculatedAmount = 0; let chargeName = ""; // Calculate charges based on type using switch case - console.log(`šŸ’° Calculating charges for type: ${chargeRecord.type}`); + // console.log(`šŸ’° Calculating charges for type: ${chargeRecord.type}`); switch (chargeRecord.type) { case "shipping_charges": calculatedAmount = calculateShippingCharges( @@ -536,7 +536,7 @@ const calculateOtherCharges = async ({ ); consolidatedCharges.deliveryFee = calculatedAmount; chargeName = "Delivery Fee"; - console.log(`āœ… Shipping charges calculated: ${calculatedAmount}`); + // console.log(`āœ… Shipping charges calculated: ${calculatedAmount}`); break; case "haze_platform_fee": @@ -546,7 +546,7 @@ const calculateOtherCharges = async ({ ); consolidatedCharges.hazePlatformFee = calculatedAmount; chargeName = "Platform Fee"; - console.log(`āœ… Platform fee calculated: ${calculatedAmount}`); + // console.log(`āœ… Platform fee calculated: ${calculatedAmount}`); break; case "payment_gateway_charges": @@ -556,9 +556,9 @@ const calculateOtherCharges = async ({ ); consolidatedCharges.paymentGatewayCharges = calculatedAmount; chargeName = "Payment Gateway Charges"; - console.log( - `āœ… Payment gateway charges calculated: ${calculatedAmount}` - ); + // console.log( + // `āœ… Payment gateway charges calculated: ${calculatedAmount}` + // ); break; case "distance": @@ -568,9 +568,9 @@ const calculateOtherCharges = async ({ ); consolidatedCharges.distanceCharges = calculatedAmount; chargeName = "Distance Charges"; - console.log( - `āœ… Distance charges calculated: ${calculatedAmount} (distance: ${estimatedDistance})` - ); + // console.log( + // `āœ… Distance charges calculated: ${calculatedAmount} (distance: ${estimatedDistance})` + // ); break; case "weather": @@ -582,7 +582,7 @@ const calculateOtherCharges = async ({ chargeName = `Weather Charges${ chargeRecord.subType ? ` (${chargeRecord.subType})` : "" }`; - console.log(`āœ… Weather charges calculated: ${calculatedAmount}`); + // console.log(`āœ… Weather charges calculated: ${calculatedAmount}`); break; case "waiting_time": @@ -592,24 +592,24 @@ const calculateOtherCharges = async ({ // ); consolidatedCharges.waitingTimeCharges = calculatedAmount; chargeName = "Waiting Time Charges"; - console.log( - `āœ… Waiting time charges calculated: ${calculatedAmount} (duration: ${estimatedDuration})` - ); + // console.log( + // `āœ… Waiting time charges calculated: ${calculatedAmount} (duration: ${estimatedDuration})` + // ); break; default: - console.log( - `āš ļø Unknown charge type: ${chargeRecord.type} - skipping` - ); + // console.log( + // `āš ļø Unknown charge type: ${chargeRecord.type} - skipping` + // ); continue; } // Add to charges breakdown if amount is greater than 0 console.log(`šŸ“ Charge amount for ${chargeName}: ${calculatedAmount}`); if (calculatedAmount > 0) { - console.log( - `āœ… Adding ${chargeName} to breakdown (amount: ${calculatedAmount})` - ); + // console.log( + // `āœ… Adding ${chargeName} to breakdown (amount: ${calculatedAmount})` + // ); const chargeBreakdownItem = { type: chargeRecord.type, name: chargeName, @@ -623,9 +623,9 @@ const calculateOtherCharges = async ({ // Track surcharges separately if (chargeRecord.isSurcharge) { - console.log( - `šŸ·ļø Adding to surcharges: ${chargeName} (${calculatedAmount})` - ); + // console.log( + // `šŸ·ļø Adding to surcharges: ${chargeName} (${calculatedAmount})` + // ); totalSurcharges += calculatedAmount; surchargeBreakdown.push({ type: chargeRecord.type, @@ -642,9 +642,9 @@ const calculateOtherCharges = async ({ } } - console.log("\nšŸ“Š Final consolidated charges:", consolidatedCharges); - console.log("šŸ“Š Total surcharges:", totalSurcharges); - console.log("šŸ“Š Surcharge breakdown:", surchargeBreakdown); + // console.log("\nšŸ“Š Final consolidated charges:", consolidatedCharges); + // console.log("šŸ“Š Total surcharges:", totalSurcharges); + // console.log("šŸ“Š Surcharge breakdown:", surchargeBreakdown); const finalResult = { shippingCharges: consolidatedCharges.deliveryFee, @@ -654,7 +654,7 @@ const calculateOtherCharges = async ({ surchargeDetails: surchargeBreakdown, }; - console.log("šŸŽÆ Final calculateOtherCharges result:", finalResult); + // console.log("šŸŽÆ Final calculateOtherCharges result:", finalResult); return finalResult; } catch (error) { throw new Error(`Error calculating other charges: ${error.message}`); @@ -807,7 +807,7 @@ const calculateCartSummary = async ({ options = {}, customerState = null, storeId = null, - tipAmount, + tipAmount=0, }) => { // Validate cartItems if (!cartItems || !Array.isArray(cartItems) || cartItems.length === 0) { @@ -912,7 +912,7 @@ const calculateCartSummary = async ({ estimatedDuration, tipAmount, }); - console.log("chargesInfo", chargesInfo); + // console.log("chargesInfo", chargesInfo); } catch (error) { throw new Error(`Error calculating other charges: ${error.message}`); } @@ -940,7 +940,7 @@ const calculateCartSummary = async ({ message: "All contributions calculation failed", }; } - console.log("āœ… All contributions calculated:", allContributions); + // console.log("āœ… All contributions calculated:", allContributions); } catch (error) { console.error("āŒ Error calculating all contributions:", error); // Set default contribution structure if calculation fails @@ -1038,7 +1038,6 @@ const calculateCartSummary = async ({ ? profitBreakdown.contributions.shipping.customer : 0; - // console.log("appliedShippCharges", appliedShippCharges); //Order calculations const finalTotal = @@ -1450,7 +1449,7 @@ const recoverStockFromCart = async (cartItems, storeId, options = {}) => { variantId ); - console.log("actualVariantId", actualVariantId); + // console.log("actualVariantId", actualVariantId); // āœ… DIRECT LOOKUP: Find stock record using actual variant ID const stockRecord = productStoreStocks.find( (stock) => @@ -1458,7 +1457,7 @@ const recoverStockFromCart = async (cartItems, storeId, options = {}) => { stock.variationId === actualVariantId ); - console.log("stockRecord", stockRecord); + // console.log("stockRecord", stockRecord); if (!stockRecord) { recoveryResults.push({ @@ -1662,7 +1661,7 @@ const checkStockAvailability = async (cartItems, storeId, options = {}) => { (user.role === "super-admin" || user.role === "store-admin" || user.isSuperAdminEmployee === true); - console.log("cartitems in checkStockAvailability - PRODUCT TYPE APPROACH"); + // console.log("cartitems in checkStockAvailability - PRODUCT TYPE APPROACH"); try { const availabilityResults = []; // :white_tick: NEW APPROACH: Collect all product IDs for bulk queries @@ -1722,9 +1721,9 @@ const checkStockAvailability = async (cartItems, storeId, options = {}) => { variationId: { [Op.in]: uniqueVariantIds }, }, }); - console.log("Products found:", products.length); - console.log("Variants found:", variants.length); - console.log("Stock records found:", productStoreStocks.length); + // console.log("Products found:", products.length); + // console.log("Variants found:", variants.length); + // console.log("Stock records found:", productStoreStocks.length); // Process each cart item for (const item of cartItems) { const { cartItemId, productId, variantId, quantity } = item; @@ -1774,12 +1773,12 @@ const checkStockAvailability = async (cartItems, storeId, options = {}) => { (stock) => stock.productId === productId && stock.variationId === actualVariantId ); - console.log("Processing item:", { - productId, - variantId, - actualVariantId, - }); - console.log("Stock found:", !!stockInfo); + // console.log("Processing item:", { + // productId, + // variantId, + // actualVariantId, + // }); + // console.log("Stock found:", !!stockInfo); if (!stockInfo) { availabilityResults.push({ cartItemId, diff --git a/utils/contributionUtils.js b/utils/contributionUtils.js index 5a2ebc5e46a4afa72a37724533b4d19b6664116b..b82353db23edf3946f15bfc6a7cafd7cab41d0c0 100644 --- a/utils/contributionUtils.js +++ b/utils/contributionUtils.js @@ -21,17 +21,17 @@ const calculateMultipleContributions = async ({ tipAmount, }) => { try { - console.log("šŸ”„ calculateMultipleContributions - Starting with data:", { - shippingCharges, - tipAmount, - }); + // console.log("šŸ”„ calculateMultipleContributions - Starting with data:", { + // shippingCharges, + // tipAmount, + // }); // Get all active distribution modes const activeModes = await getAllDistributionModesService({ where: { isActive: true }, }); - console.log(`šŸ“Š Found ${activeModes.length} active distribution modes`); + // console.log(`šŸ“Š Found ${activeModes.length} active distribution modes`); if (!activeModes || activeModes.length === 0) { return { @@ -54,9 +54,9 @@ const calculateMultipleContributions = async ({ // Process each active mode using Promise.all for better performance const contributionPromises = activeModes.map(async (mode) => { try { - console.log( - `šŸ” Processing mode: ${mode.modeName} (${mode.distributionOn})` - ); + // console.log( + // `šŸ” Processing mode: ${mode.modeName} (${mode.distributionOn})` + // ); let contributionResult = null; let contributionKey = mode.distributionOn; @@ -95,7 +95,7 @@ const calculateMultipleContributions = async ({ break; default: - console.log(`āš ļø Unknown distribution type: ${mode.distributionOn}`); + // console.log(`āš ļø Unknown distribution type: ${mode.distributionOn}`); contributionResult = { status: false, message: "Unknown distribution type", @@ -153,22 +153,22 @@ const calculateMultipleContributions = async ({ // Handle different contribution types if (key === "tip") { // Tip distributions don't contribute to customer/store/admin totals in the same way - console.log(`āœ… Added tip distribution for ${key}:`, { - driver: result.driverDistribution || 0, - admin: result.adminDistribution || 0, - store: result.storeDistribution || 0, - }); + // console.log(`āœ… Added tip distribution for ${key}:`, { + // driver: result.driverDistribution || 0, + // admin: result.adminDistribution || 0, + // store: result.storeDistribution || 0, + // }); } else { // Handle shipping and other contributions totalCustomerContribution += result.customerContribution || 0; totalStoreContribution += result.storeContribution || 0; totalAdminContribution += result.adminContribution || 0; - console.log(`āœ… Added contribution for ${key}:`, { - customer: result.customerContribution || 0, - store: result.storeContribution || 0, - admin: result.adminContribution || 0, - }); + // console.log(`āœ… Added contribution for ${key}:`, { + // customer: result.customerContribution || 0, + // store: result.storeContribution || 0, + // admin: result.adminContribution || 0, + // }); } } else { console.log(`āš ļø Contribution calculation failed for ${key}:`, result.message); @@ -198,10 +198,10 @@ const calculateMultipleContributions = async ({ }, }; - console.log( - "šŸŽÆ calculateMultipleContributions - Final result:", - finalResult - ); + // console.log( + // "šŸŽÆ calculateMultipleContributions - Final result:", + // finalResult + // ); return finalResult; } catch (error) { console.error("āŒ Error in calculateMultipleContributions:", error); diff --git a/utils/distributionValidation.js b/utils/distributionValidation.js index 64b45d1bac3088fa81eac13ea6f90771699d1edc..35fde2e65cff0d3c27120092f86d5712db9b44f5 100644 --- a/utils/distributionValidation.js +++ b/utils/distributionValidation.js @@ -22,14 +22,14 @@ const getShippingCharges = async (transaction = null, payloadSettings = null) => setting => setting.type === "shipping_charges" && setting.isActive ); if (payloadShippingSettings.length > 0) { - console.log("Using shipping_charges from payload:", payloadShippingSettings); + // console.log("Using shipping_charges from payload:", payloadShippingSettings); shippingSettings = payloadShippingSettings; } } // If not found in payload, get from database if (shippingSettings.length === 0) { - console.log("No shipping_charges in payload, fetching from database"); + // console.log("No shipping_charges in payload, fetching from database"); shippingSettings = await getAllSettingsService({ where: { type: ["shipping_charges"], @@ -37,7 +37,7 @@ const getShippingCharges = async (transaction = null, payloadSettings = null) => }, transaction, }); - console.log("Found shipping_charges in database:", shippingSettings); + // console.log("Found shipping_charges in database:", shippingSettings); } // Calculate total shipping charges @@ -51,7 +51,7 @@ const getShippingCharges = async (transaction = null, payloadSettings = null) => // This depends on your business logic for how percentages are applied } - console.log("Total shipping charges calculated:", totalShippingCharges); + // console.log("Total shipping charges calculated:", totalShippingCharges); return totalShippingCharges; } catch (error) { console.error("Error getting shipping charges:", error); diff --git a/utils/orderCreation.js b/utils/orderCreation.js index 11d95eaf681dc9f51609261ec40efe799156cdf2..18772e9a2eaf25da6f33e6d1752b9ef88f4159f0 100644 --- a/utils/orderCreation.js +++ b/utils/orderCreation.js @@ -53,7 +53,7 @@ const createOrder = async ({ let makePayment = null; let orderId; try { - console.log("Starting order creation process..."); + // console.log("Starting order creation process..."); // 1. Validate payment method and token if ( @@ -71,7 +71,7 @@ const createOrder = async ({ throw new Error("Cart not found"); } - console.log("cartttttt", cart); + // console.log("cartttttt", cart); if (!barcode) { throw new Error("Barcode is required for order creation"); @@ -111,7 +111,7 @@ const createOrder = async ({ ], transaction: t, }); - console.log("cartItemsssss", cartItems); + // console.log("cartItemsssss", cartItems); // For single products without variants, fetch the default variant for (let i = 0; i < cartItems.length; i++) { @@ -137,7 +137,7 @@ const createOrder = async ({ cartItems = cartItems ? cartItems.map((item) => item.get({ plain: true })) : null; - console.log("cartItemsssss", cartItems); + // console.log("cartItemsssss", cartItems); if (!cartItems || cartItems.length === 0) { throw new Error("Cart is empty"); } @@ -157,7 +157,7 @@ const createOrder = async ({ deliveryMethod: deliveryMethod, tipAmount, }); - console.log("cartSummary", cartSummary); + // console.log("cartSummary", cartSummary); const totalAmount = cartSummary.totalAmount; @@ -252,8 +252,8 @@ const createOrder = async ({ country: cart?.shipping_country, postcode: cart?.shipping_zip, }; - console.log("payBillAddress", payBillAddress); - console.log("payShipAddress", payShipAddress); + // console.log("payBillAddress", payBillAddress); + // console.log("payShipAddress", payShipAddress); // Process payment based on method if (paymentMethod === "card" && paymentToken) { @@ -318,7 +318,7 @@ const createOrder = async ({ remainingBalance: 1000 - totalAmount, }; - console.log("šŸ¦ Dummy wallet payment processed:", paymentResult); + // console.log("šŸ¦ Dummy wallet payment processed:", paymentResult); } else if (paymentMethod === "cod") { // Cash on Delivery - no payment processing needed paymentResult = { @@ -330,7 +330,7 @@ const createOrder = async ({ approvedMoney: totalAmount, }; - console.log("šŸ’µ COD payment registered:", paymentResult); + // console.log("šŸ’µ COD payment registered:", paymentResult); } else { // Unknown payment method throw new Error(`Unsupported payment method: ${paymentMethod}`); @@ -399,7 +399,7 @@ const createOrder = async ({ transaction: t, }); - console.log("cartSummary.tipDistribution", cartSummary.tipDistribution); + // console.log("cartSummary.tipDistribution", cartSummary.tipDistribution); // 11. Create transaction record for the order try { diff --git a/utils/profitCalculator.js b/utils/profitCalculator.js index cb8a6d69af4c4e8971658231949b6180ad697e33..2903ed02a08d3d4f95d1a958ff1eae4df1aca241 100644 --- a/utils/profitCalculator.js +++ b/utils/profitCalculator.js @@ -80,7 +80,7 @@ const calculateStoreProfit = async ({ // Calculate profit from product sales for (const item of cartItems) { try { - console.log("Processing item in calculateStoreProfit:", item); + // console.log("Processing item in calculateStoreProfit:", item); const { productId, variantId, quantity, unitPrice } = item; // Validate item data @@ -96,23 +96,23 @@ const calculateStoreProfit = async ({ variantId, storeId, }); - console.log("costPrice", costPrice); - console.log("unitPrice", unitPrice); + // console.log("costPrice", costPrice); + // console.log("unitPrice", unitPrice); // Calculate profit per unit const profitPerUnit = parseFloat(unitPrice) - parseFloat(costPrice); - console.log("profitPerUnit", profitPerUnit); + // console.log("profitPerUnit", profitPerUnit); // Calculate total profit for this item const itemProfit = profitPerUnit * parseInt(quantity); - console.log("itemProfit", itemProfit); + // console.log("itemProfit", itemProfit); totalStoreProfit += itemProfit; - console.log( - `Store Profit - Product ${productId}, Variant ${variantId}:`, - itemProfit - ); + // console.log( + // `Store Profit - Product ${productId}, Variant ${variantId}:`, + // itemProfit + // ); } catch (itemError) { const error = `Error processing item ${item.productId}: ${itemError.message}`; console.error(error); @@ -137,7 +137,7 @@ const calculateStoreProfit = async ({ itemProfits, }; - console.log("Store Profit Breakdown:", profitBreakdown); + // console.log("Store Profit Breakdown:", profitBreakdown); // Return result with error information return { @@ -213,15 +213,15 @@ const calculateAllProfits = async ({ tipDistribution = {}, }) => { try { - console.log("Starting profit calculation with params:", { - cartItemsCount: cartItems.length, - storeId, - hazePlatformFee, - shippingCharges, - surcharges, - shippingContribution, - tipDistribution, - }); + // console.log("Starting profit calculation with params:", { + // cartItemsCount: cartItems.length, + // storeId, + // hazePlatformFee, + // shippingCharges, + // surcharges, + // shippingContribution, + // tipDistribution, + // }); // Validate required parameters if (!cartItems || !Array.isArray(cartItems) || cartItems.length === 0) { @@ -329,7 +329,7 @@ const calculateAllProfits = async ({ }, }; - console.log("Profit calculation completed:", profitBreakdown); + // console.log("Profit calculation completed:", profitBreakdown); return { status: !hasErrors, @@ -373,13 +373,13 @@ const calculateProfitsFromCartSummary = async ({ tipDistribution = {}, }) => { try { - console.log("calculateProfitsFromCartSummary called with:", { - chargesInfo: chargesInfo ? "provided" : "missing", - cartItemsCount: processedCartItems?.length || 0, - storeId: calculationStoreId, - shippingContribution, - tipDistribution, - }); + // console.log("calculateProfitsFromCartSummary called with:", { + // chargesInfo: chargesInfo ? "provided" : "missing", + // cartItemsCount: processedCartItems?.length || 0, + // storeId: calculationStoreId, + // shippingContribution, + // tipDistribution, + // }); // Validate required parameters if (!chargesInfo) { @@ -416,7 +416,7 @@ const calculateProfitsFromCartSummary = async ({ warnings: profitResult.warnings || null, }; - console.log("calculateProfitsFromCartSummary result:", result); + // console.log("calculateProfitsFromCartSummary result:", result); return result; } catch (error) { console.error("Error calculating profits from cart summary:", error); diff --git a/utils/transactionPaymentUtils.js b/utils/transactionPaymentUtils.js index f32a49dfa1b6753d55aed09691b91f8f54a1593d..27ccdc3327c75daa3cca06f5b61022ca0291f519 100644 --- a/utils/transactionPaymentUtils.js +++ b/utils/transactionPaymentUtils.js @@ -49,15 +49,15 @@ module.exports.createStoreAndAdminPaymentDetails = async ({ payment_ref_no: payment_id, }; - console.log("hazeProfit", hazeProfit); - console.log("storeProfit", storeProfit); + // console.log("hazeProfit", hazeProfit); + // console.log("storeProfit", storeProfit); // Validate profit amounts const validHazeProfit = parseFloat(hazeProfit) || 0; const validStoreProfit = parseFloat(storeProfit) || 0; - console.log("validHazeProfit", validHazeProfit); - console.log("validStoreProfit", validStoreProfit); + // console.log("validHazeProfit", validHazeProfit); + // console.log("validStoreProfit", validStoreProfit); if (validHazeProfit < 0 || validStoreProfit < 0) { throw new Error("Profit amounts cannot be negative"); @@ -82,9 +82,9 @@ module.exports.createStoreAndAdminPaymentDetails = async ({ entity: "store", }; - console.log("Admin payload:", JSON.stringify(adminPayload, null, 2)); - console.log("Store payload:", JSON.stringify(storePayload, null, 2)); - console.log("Transaction options:", { transaction }); + // console.log("Admin payload:", JSON.stringify(adminPayload, null, 2)); + // console.log("Store payload:", JSON.stringify(storePayload, null, 2)); + // console.log("Transaction options:", { transaction }); // Create both records in parallel using service const [adminPaymentDetails, storePaymentDetails] = await Promise.all([ diff --git a/validators/brand.validator.js b/validators/brand.validator.js index fdabacb0d6eddb7d3c583bfe68d8895a701586b8..431286799106cfdb105720c64ad5aa93e3fbc0f5 100644 --- a/validators/brand.validator.js +++ b/validators/brand.validator.js @@ -65,14 +65,14 @@ const validateBrandDataFields = (body, files) => { // Validation middleware const validateBrandData = (req, res, next) => { try { - console.log("=== VALIDATING BRAND==="); - console.log("Body fields:", Object.keys(req.body)); - console.log("Body data:", req.body); - console.log( - "File fields:", - req.files ? Object.keys(req.files) : "No files" - ); - console.log("========================================"); + // console.log("=== VALIDATING BRAND==="); + // console.log("Body fields:", Object.keys(req.body)); + // console.log("Body data:", req.body); + // console.log( + // "File fields:", + // req.files ? Object.keys(req.files) : "No files" + // ); + // console.log("========================================"); // Ensure req.body exists if (!req.body) { @@ -172,14 +172,14 @@ const updateBrandValidator = Joi.object({ // Validation middleware for update const validateUpdateBrandData = (req, res, next) => { try { - console.log("=== VALIDATING BRAND UPDATE==="); - console.log("Body fields:", Object.keys(req.body)); - console.log("Body data:", req.body); - console.log( - "File fields:", - req.files ? Object.keys(req.files) : "No files" - ); - console.log("========================================"); + // console.log("=== VALIDATING BRAND UPDATE==="); + // console.log("Body fields:", Object.keys(req.body)); + // console.log("Body data:", req.body); + // console.log( + // "File fields:", + // req.files ? Object.keys(req.files) : "No files" + // ); + // console.log("========================================"); // Ensure req.body exists if (!req.body) { diff --git a/validators/customer.validator.js b/validators/customer.validator.js index 57ddceaaf3085baed57c3eb71102d3391cff73c2..a6d37073ede9f71220c317fa67ec4353f1bd2fa4 100644 --- a/validators/customer.validator.js +++ b/validators/customer.validator.js @@ -1278,13 +1278,13 @@ const validateAgeVerificationFormData = (body, files) => { // Validation middleware for age verification const validateAgeVerification = (req, res, next) => { try { - console.log("=== VALIDATING AGE VERIFICATION ==="); - console.log("Body fields:", Object.keys(req.body)); - console.log( - "File fields:", - req.files ? Object.keys(req.files) : "No files" - ); - console.log("==================================="); + // console.log("=== VALIDATING AGE VERIFICATION ==="); + // console.log("Body fields:", Object.keys(req.body)); + // console.log( + // "File fields:", + // req.files ? Object.keys(req.files) : "No files" + // ); + // console.log("==================================="); // First validate FormData structure const formDataValidation = validateAgeVerificationFormData( diff --git a/validators/stockAdjustment.validator.js b/validators/stockAdjustment.validator.js index 5ac9e1566f2e84f88199c26b9c3a0d9d65122b2b..209f3b726a2ac636ff01d23a901d44ccf0dece0d 100644 --- a/validators/stockAdjustment.validator.js +++ b/validators/stockAdjustment.validator.js @@ -202,14 +202,14 @@ const validateCreateStockAdjustment = (req, res, next) => { const negativeAdjustments = adjustmentLines.filter(line => line.quantity < 0); if (negativeAdjustments.length > 0) { // Log for tracking offline sales and other stock reductions - console.log(`Stock reduction requested for ${negativeAdjustments.length} items:`, - negativeAdjustments.map(line => ({ - productId: line.productId, - variationId: line.variationId, - quantity: line.quantity, - reason: line.reason - })) - ); + // console.log(`Stock reduction requested for ${negativeAdjustments.length} items:`, + // negativeAdjustments.map(line => ({ + // productId: line.productId, + // variationId: line.variationId, + // quantity: line.quantity, + // reason: line.reason + // })) + // ); } // Validate positive quantities (stock increase) diff --git a/validators/store.validator.js b/validators/store.validator.js index 33329d10633baee71ddd4d4524442b5bf732be78..4946bbc2372f855db185b1533dfd0128dda1ee4c 100644 --- a/validators/store.validator.js +++ b/validators/store.validator.js @@ -922,13 +922,13 @@ const validateStoreSectionCreation = (req, res, next) => { // Validation middleware for complete store creation const validateCustomerRegistration = (req, res, next) => { try { - console.log("=== VALIDATING STORE CREATION ==="); - console.log("Body fields:", Object.keys(req.body)); - console.log( - "File fields:", - req.files ? Object.keys(req.files) : "No files" - ); - console.log("========================================"); + // console.log("=== VALIDATING STORE CREATION ==="); + // console.log("Body fields:", Object.keys(req.body)); + // console.log( + // "File fields:", + // req.files ? Object.keys(req.files) : "No files" + // ); + // console.log("========================================"); // First validate FormData structure const formDataValidation = validateStoreFormDataFields(req.body, req.files); diff --git a/validators/user.validator.js b/validators/user.validator.js index 70ffd02adeb886e957d853bc2daddebcfe0c883c..bf9f8f0124ac8bca07385ec7802a0a10ec68c721 100644 --- a/validators/user.validator.js +++ b/validators/user.validator.js @@ -502,13 +502,13 @@ const validateFormDataFields = (body, files) => { const validateStoreAdminRegistartion = (req, res, next) => { try { - console.log("=== VALIDATING STORE ADMIN ==="); - console.log("Body fields:", Object.keys(req.body)); - console.log( - "File fields:", - req.files ? Object.keys(req.files) : "No files" - ); - console.log("========================================"); + // console.log("=== VALIDATING STORE ADMIN ==="); + // console.log("Body fields:", Object.keys(req.body)); + // console.log( + // "File fields:", + // req.files ? Object.keys(req.files) : "No files" + // ); + // console.log("========================================"); // First validate FormData structure const formDataValidation = validateFormDataFields(req.body, req.files);