const productData: CreateProductInput = req.body;
// Adjust price if necessary
let adjustedPrice = productData.price;
if (productData.price < 1000) {
adjustedPrice = parseFloat((productData.price * 1000).toFixed(2));
}
console.log("Inserting product with adjusted price:", adjustedPrice);
// Insert product
const productResult = await query(
`INSERT INTO products (name, description, brand_id, has_color, has_size, product_type, price, qty, sold, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
RETURNING id, created_at, updated_at`,
[
productData.name,
productData.description,
productData.brand_id,
Boolean(productData.has_color),
Boolean(productData.has_size),
productData.product_type,
adjustedPrice,
productData.qty
]
);
const productId = productResult.rows[0].id;
console.log(`Inserted product ID: ${productId}`);
// Insert category associations
const categoryInsertPromises = productData.category_ids.map((categoryId: number) => {
console.log(`Associating category ID ${categoryId} with product ID ${productId}`);
return query(
`INSERT INTO product_categories (product_id, category_id)
VALUES ($1, $2)`,
[productId, categoryId]
);
});
await Promise.all(categoryInsertPromises);
console.log('Inserted all category associations.');
// Insert images
const imagesInsertPromises = productData.images.map((image: ImageInput) => {
console.log(`Inserting product image: ${image.url}`);
return query(
`INSERT INTO images (product_id, url, color_id, size_id)
VALUES ($1, $2, $3, $4)
RETURNING id, color_id, size_id, url`,
[productId, image.url, image.color_id || null, image.size_id || null]
);
});
const insertedImagesResults = await Promise.all(imagesInsertPromises);
const insertedImages = insertedImagesResults.map((imgResult: any) => ({
id: imgResult.rows[0].id,
url: imgResult.rows[0].url,
color_id: imgResult.rows[0].color_id,
size_id: imgResult.rows[0].size_id
}));
console.log(`Inserted ${insertedImages.length} product images.`);
// Handle colors and sizes based on product type
const insertedColors: number[] = [];
const insertedSizes: number[] = [];
if (productData.has_color && productData.colors) {
for (const color of productData.colors) {
// Adjust color price if necessary
let adjustedColorPrice = color.price;
if (color.price < 1000) {
adjustedColorPrice = parseFloat((color.price * 1000).toFixed(2));
}
console.log(`Inserting color: ${color.name} with has_size: ${color.has_size}`);
// Insert color with explicit boolean casting
const colorResult = await query(
`INSERT INTO colors (product_id, name, price, qty, sold, has_size)
VALUES ($1, $2, $3, $4, 0, $5)
RETURNING id, has_size`,
[productId, color.name, adjustedColorPrice, color.qty, Boolean(color.has_size)]
);
const colorId = colorResult.rows[0].id;
const colorHasSize = colorResult.rows[0].has_size;
console.log(`Inserted color ID=${colorId}, has_size=${colorHasSize}`);
insertedColors.push(colorId);
// Insert color images
const colorImagesInsertPromises = color.images.map((image: ImageInput) => {
console.log(`Inserting color image: ${image.url}`);
return query(
`INSERT INTO images (product_id, color_id, url, size_id)
VALUES ($1, $2, $3, $4)
RETURNING id, color_id, size_id, url`,
[productId, colorId, image.url, image.size_id || null]
);
});
const insertedColorImagesResults = await Promise.all(colorImagesInsertPromises);
console.log(`Inserted ${insertedColorImagesResults.length} images for color ID=${colorId}`);
if (color.has_size && color.sizes) {
for (const size of color.sizes) {
// Adjust size price if necessary
let adjustedSizePrice = size.price;
if (size.price < 1000) {
adjustedSizePrice = parseFloat((size.price * 1000).toFixed(2));
}
console.log(`Inserting size: ${size.name} with price: ${adjustedSizePrice}`);
// Insert size
const sizeResult = await query(
`INSERT INTO sizes (product_id, color_id, name, price, qty, sold)
VALUES ($1, $2, $3, $4, $5, 0)
RETURNING id`,
[productId, colorId, size.name, adjustedSizePrice, size.qty]
);
const sizeId = sizeResult.rows[0].id;
console.log(`Inserted size ID=${sizeId} for color ID=${colorId}`);
insertedSizes.push(sizeId);
// Insert size images
const sizeImagesInsertPromises = size.images.map((image: ImageInput) => {
console.log(`Inserting size image: ${image.url}`);
return query(
`INSERT INTO images (product_id, color_id, size_id, url)
VALUES ($1, $2, $3, $4)
RETURNING id, color_id, size_id, url`,
[productId, colorId, sizeId, image.url]
);
});
const insertedSizeImagesResults = await Promise.all(sizeImagesInsertPromises);
console.log(`Inserted ${insertedSizeImagesResults.length} images for size ID=${sizeId}`);
}
}
}
} else if (productData.has_size && productData.sizes) {
for (const size of productData.sizes) {
// Adjust size price if necessary
let adjustedSizePrice = size.price;
if (size.price < 1000) {
adjustedSizePrice = parseFloat((size.price * 1000).toFixed(2));
}
console.log(`Inserting standalone size: ${size.name} with price: ${adjustedSizePrice}`);
// Insert size
const sizeResult = await query(
`INSERT INTO sizes (product_id, name, price, qty, sold)
VALUES ($1, $2, $3, $4, 0)
RETURNING id`,
[productId, size.name, adjustedSizePrice, size.qty]
);
const sizeId = sizeResult.rows[0].id;
console.log(`Inserted standalone size ID=${sizeId}`);
insertedSizes.push(sizeId);
// Insert size images
const sizeImagesInsertPromises = size.images.map((image: ImageInput) => {
console.log(`Inserting standalone size image: ${image.url}`);
return query(
`INSERT INTO images (product_id, size_id, url)
VALUES ($1, $2, $3)
RETURNING id, color_id, size_id, url`,
[productId, sizeId, image.url]
);
});
const insertedSizeImagesResults = await Promise.all(sizeImagesInsertPromises);
console.log(`Inserted ${insertedSizeImagesResults.length} images for standalone size ID=${sizeId}`);
}
}
// Construct the new product object as it would appear in the cache
const newProduct: Product = {
id: productId,
name: productData.name,
description: productData.description,
brand_id: productData.brand_id,
has_color: productData.has_color,
has_size: productData.has_size,
product_type: productData.product_type,
price: adjustedPrice,
qty: productData.qty,
sold: 0,
created_at: productResult.rows[0].created_at.toISOString(),
updated_at: productResult.rows[0].updated_at.toISOString(),
categories: productData.category_ids.map((cid: number) => ({
id: cid,
name: "", // Optional: Fetch and populate category names
main_category_id: 0, // Optional: Set appropriately
main_category_name: "" // Optional: Set appropriately
})),
colors: productData.has_color && productData.colors ? productData.colors.map((color, index) => ({
id: insertedColors[index],
name: color.name,
price: color.price || 0,
qty: color.qty,
sold: 0,
has_size: Boolean(color.has_size),
sizes: Boolean(color.has_size) && color.sizes ? color.sizes.map((size, sIndex) => ({
id: insertedSizes[sIndex],
name: size.name,
price: size.price,
qty: size.qty,
sold: 0,
color_id: null, // Optional: Set if needed
images: size.images.map(img => img.url)
})) : [],
images: color.images.map(img => img.url)
})) : [],
sizes: productData.has_size && !productData.has_color && productData.sizes ? productData.sizes.map((size, index) => ({
id: insertedSizes[index],
name: size.name,
price: size.price,
qty: size.qty,
sold: 0,
color_id: null,
images: size.images.map(img => img.url)
})) : [],
images: insertedImages
};
console.log("New product to cache:", newProduct); // Log new product
// Update the cache
addProductToCache(newProduct);
await query('COMMIT');
res.status(201).json({ message: 'Product added successfully!', productId });
export interface BrandsCacheData {
allBrands: Brand[];
export const loadAndCacheAllProducts = async (): Promise => {
const q = SELECT p.id, p.name, p.description, p.brand_id, p.has_color, p.has_size, p.product_type, p.price, p.qty, p.sold, p.created_at, p.updated_at, sc.id AS subcategory_id, sc.name AS subcategory_name, c.id AS main_category_id, c.name AS main_category_name, s.id AS size_id, s.name AS size_name, s.price AS size_price, s.qty AS size_qty, s.sold AS size_sold, cl.id AS color_id, cl.name AS color_name, cl.price AS color_price, cl.qty AS color_qty, cl.sold AS color_sold, i.id AS image_id, i.url AS image_url, i.color_id AS image_color_id, i.size_id AS image_size_id FROM products p LEFT JOIN product_categories pc ON p.id = pc.product_id LEFT JOIN subcategories sc ON pc.category_id = sc.id LEFT JOIN categories c ON sc.category_id = c.id LEFT JOIN sizes s ON p.id = s.product_id LEFT JOIN colors cl ON p.id = cl.product_id LEFT JOIN images i ON (p.id = i.product_id AND (cl.id = i.color_id OR i.color_id IS NULL) AND (s.id = i.size_id OR i.size_id IS NULL)) ;