Skip to content

Commit

Permalink
Merge pull request #31 from danial117/server_dev_11
Browse files Browse the repository at this point in the history
commit
  • Loading branch information
danial117 committed Aug 28, 2024
2 parents 5d58743 + a49eb17 commit c9eab1a
Show file tree
Hide file tree
Showing 16 changed files with 555 additions and 99 deletions.
Empty file.
166 changes: 163 additions & 3 deletions controllers/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,15 @@ import { generateAccessToken,generateAdminRefreshToken } from "../middlewares/au
import { generateOtp,isOtpValid } from "../utils/otp.js";
import { sendAdminOTPMail } from "../middlewares/nodemailer.js";
import Brand from "../models/BrandModel.js";
import csvParser from 'csv-parser';
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url';
import { compressAndSaveProductImage } from "../utils/compressImages.js";




// Get current file directory
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);



Expand Down Expand Up @@ -215,4 +220,159 @@ export const VerifyOTP=async(req,res)=>{
console.log(error)
res.status(500).json({ error: 'Error verifying OTP' });
}
}







export const AdminCsvFileHandling = (req, res) => {
const results = [];

if (!req.file) {
return res.status(400).send('No file uploaded.');
}

// Read and parse the uploaded CSV file
fs.createReadStream(req.file.path)
.pipe(csvParser())
.on('data', (row) => {
// Preprocess the row to remove quotes and trim whitespace
const cleanedRow = {};
for (let key in row) {
// Remove any leading/trailing whitespace and extraneous quotes
cleanedRow[key.trim()] = row[key].trim().replace(/^"|"$/g, '');
}
// Push the cleaned row into the results array
results.push(cleanedRow);
})
.on('end', async () => {
try {
for (const data of results) {
try {
console.log(data);
const options = data.option.split(',').reduce((acc, opt, index) => {
const price = data.price.split(',')[index];
if (price) {
acc.push({
option: opt.trim(),
price: price.trim(),
});
}
return acc;
}, []);
// Create a new product based on the CSV data
const product = new Product({
name: data.name,
brand: data.brand,
brandId: data.brandId, // Adjust based on CSV structure
productImage: data.productImage,
category: data.category ? data.category.split(',') : [],
options: options,
details: {
Description: data.Description,
Warnings: data.Warnings,
More: data.More,
DietaryRestrictions: data.DietaryRestrictions ? data.DietaryRestrictions.split(',') : [],
Certifications: data.Certifications ? data.Certifications.split(',') : [],
},
});

// Save the product to the database
await product.save();
console.log(`Product ${data.name} saved successfully.`);
} catch (error) {
console.error(`Error saving product ${data.name}: ${error.message}`);
// Optionally, you could store failed items in a separate array or log them for further inspection
}
}


res.status(200).send('CSV file processed and data saved successfully.');
} catch (error) {
console.error('Error saving data:', error);
res.status(500).send('Error processing CSV file.');
} finally {

fs.unlinkSync(req.file.path);
}
});
};






export const AdminUploadImagesFolder=async (req,res)=>{

try {
const files = req.files;
const matchedFiles = [];
const productsDir = path.join(__dirname, '../public/products/large');

// Iterate over the uploaded files
for (let file of files) {

const product = await Product.findOne({ productImage: file.originalname });

if (product) {
const newFilename = `${Date.now()}-${file.originalname.replace(/ /g, '_').replace('.png', '_large.png')}`;

const newPath = path.join(productsDir, newFilename);
console.log(newPath)


// Move the file to the new location with the new name
fs.rename(file.path, newPath, async(err) => {
if (err) {
console.error(`Failed to rename and move file: ${err.message}`);
} else {
console.log('fix')
const {outputMediumFileName,outputSmallFileName}=await compressAndSaveProductImage(newFilename)
product.productImage={
large:newFilename,
medium:outputMediumFileName,
small:outputSmallFileName
}

await product.save()






}
});


matchedFiles.push({ ...file, newFilename });

} else {
// If no match, delete the file
fs.unlinkSync(file.path);
}
}

// If no files matched, send a response indicating no files were saved
if (matchedFiles.length === 0) {
return res.status(400).json({ message: 'No files matched with any product images.' });
}else{
for (let file of matchedFiles){
console.log(matchedFiles)
fs.unlinkSync(file.path);
}

}

// Pass the matched files to the next middleware/controller


} catch (error) {
console.log(error)
return res.status(500).json({ error: error.message });
}
}
5 changes: 4 additions & 1 deletion controllers/brand.js
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,10 @@ export const GetBrandProducts=async(req,res)=>{


if(brand){
const products=await Product.find({brand:brand.name}).skip(skip).limit(limit);
const products=await Product.find({brand:brand.name,$nor: [
{ productImage: { $type: "string" } },
{ productImage: "" }
]}).skip(skip).limit(limit);

res.status(200).json(products)
}else{
Expand Down
3 changes: 2 additions & 1 deletion controllers/cart.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import Product from "../models/ProductModel.js";
export const AddToCart = async (req, res) => {
const { productId,quantity } = req.params;
const {userId} =req.user;
const optionId = JSON.parse(req.query.option);



Expand Down Expand Up @@ -36,7 +37,7 @@ export const AddToCart = async (req, res) => {
return res.status(404).json({ error: 'Product not found' });
}

cart.items.push({ product: productId, quantity: quantity });
cart.items.push({ product: productId, quantity: quantity,option:optionId });
await cart.save();

res.status(201).json(cart);
Expand Down
68 changes: 60 additions & 8 deletions controllers/order.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,14 @@ export const CreateUserOrder = async (req, res) => {
if(cart.items.length !== 0){
const itemsWithPrices = await Promise.all(cart.items.map(async (item) => {
const product = await Product.findById(item.product);

const selectedOption = product.options.find(option => option.id === item.option);

return {
product: item.product,
quantity: item.quantity,
price: product.price, // Get price from product model
option:item.option,
price: selectedOption ? selectedOption.price : 0, // Get price from product model
};
}));

Expand Down Expand Up @@ -261,8 +265,6 @@ function generateOrderNumber() {








Expand All @@ -272,15 +274,58 @@ function generateOrderNumber() {
const { userId } = req.user;

// Find the user's order
const order = await Order.findOne({ user: userId, orderStatus: 'Pending', orderStatus: {
$ne: 'Completed' // Not equal to 'completed'
},paymentMethod: 'Unknown' }).populate('items.product');
console.log(order)
const order = await Order.findOne({
user: userId,
orderStatus: { $ne: 'Completed' }, // Exclude completed orders
paymentMethod: 'Unknown',
}).populate('items.product');

if (!order) {
return res.status(404).json({ error: 'Order not found for user' });
}

res.status(200).json(order);
// Extract only price and option for each item
const items = order.items.map((item) => {
// Find the matching option in the product's options array
const selectedOption = item.product.options.find(select => select.id === item.option);

// If a matching option is found, return the object with the desired fields
if (selectedOption) {
return {
product:{
price: selectedOption.price,
option: selectedOption.option,
productImage: item.product.productImage,
name:item.product.name,
brand:item.product.brand,
_id:item.product._id,

}
};
}

// If no matching option is found, you can decide what to return, for example:

});

console.log(items)
// Construct the response with only the necessary fields
const response = {
orderNumber: order.orderNumber,
user: order.user,
items, // Only price and option fields are included
tax: order.tax,
paymentMethod: order.paymentMethod,
paymentStatus: order.paymentStatus,
orderStatus: order.orderStatus,
totalAmount: order.totalAmount,
itemsAmount: order.itemsAmount,
createdAt: order.createdAt,
updatedAt: order.updatedAt,
};
console.log(response)

res.status(200).json(response);
} catch (error) {
console.error('Error retrieving order:', error);
res.status(500).json({ error: 'Internal server error' });
Expand All @@ -291,6 +336,13 @@ function generateOrderNumber() {










export const CreatePaypalOrder = async (req, res) => {
try {
const { userId } = req.user; // Assuming userId is available in req.user after authentication
Expand Down
Loading

0 comments on commit c9eab1a

Please sign in to comment.