Update an existing product
*/
export const updateProduct = async (req: Request, res: Response) => {
const { id } = req.params;
const productData: UpdateProductInput = req.body;
const productId: number = parseInt(id, 10);
if (isNaN(productId)) {
return res.status(400).json({ error: 'Invalid product ID' });
}
try {
await query('BEGIN');
// Adjust product price if necessary
let adjustedProductPrice: number = productData.price;
if (adjustedProductPrice < 1000) {
adjustedProductPrice = parseFloat((adjustedProductPrice * 1000).toFixed(2));
}
// Update product details
const result = await query(
`
UPDATE products
SET
name = $1,
description = $2,
brand_id = $3,
has_color = $4,
has_size = $5,
product_type = $6,
price = $7,
qty = $8,
updated_at = CURRENT_TIMESTAMP
WHERE id = $9
RETURNING *
`,
[
productData.name,
productData.description,
productData.brand_id,
productData.has_color,
productData.has_size,
productData.product_type,
adjustedProductPrice,
productData.qty,
productId
]
);
if (result.rows.length === 0) {
await query('ROLLBACK');
return res.status(404).json({ error: 'Product not found' });
}
// Delete existing associations and data
await query('DELETE FROM product_categories WHERE product_id = $1', [productId]);
await query('DELETE FROM images WHERE product_id = $1', [productId]);
// Get existing colors and sizes
const existingColorsResult = await query('SELECT id FROM colors WHERE product_id = $1', [productId]);
const existingColorIds = new Set(existingColorsResult.rows.map((row: any) => row.id));
const existingSizesResult = await query('SELECT id FROM sizes WHERE product_id = $1', [productId]);
const existingSizeIds = new Set(existingSizesResult.rows.map((row: any) => row.id));
// Determine colors and sizes to delete
const updatedColorIds = new Set(
productData.colors
?.map((color: Color) => color.id)
.filter((id: number | undefined) => typeof id === 'number') || []
);
const colorsToDelete = [...existingColorIds].filter(id => !updatedColorIds.has(id));
const updatedSizeIds = new Set([
...(productData.sizes
?.map((size: Size) => size.id)
.filter((id: number | undefined) => typeof id === 'number') || []),
...(productData.colors?.flatMap((color: Color) =>
color.sizes.map((size: Size) => size.id).filter((id: number | undefined) => typeof id === 'number')
) || [])
]);
const sizesToDelete = [...existingSizeIds].filter(id => !updatedSizeIds.has(id));
// Delete colors and associated sizes and images
for (const colorId of colorsToDelete) {
await query('DELETE FROM sizes WHERE color_id = $1', [colorId]);
await query('DELETE FROM images WHERE color_id = $1', [colorId]);
await query('DELETE FROM colors WHERE id = $1', [colorId]);
}
// Delete sizes and associated images
for (const sizeId of sizesToDelete) {
await query('DELETE FROM images WHERE size_id = $1', [sizeId]);
await query('DELETE FROM sizes WHERE id = $1', [sizeId]);
}
// Insert category associations
if (productData.category_ids.length > 0) {
const categoryInsertPromises = productData.category_ids.map((categoryId: number) =>
query(
`INSERT INTO product_categories (product_id, category_id)
VALUES ($1, $2)`,
[productId, categoryId]
)
);
await Promise.all(categoryInsertPromises);
}
// Insert images
let insertedImages: Image[] = [];
if (productData.images.length > 0) {
const imagesInsertPromises = productData.images.map((image: ImageInput) =>
query(
`INSERT INTO images (product_id, url, color_id, size_id)
VALUES ($1, $2, $3, $4)
RETURNING id, url, color_id, size_id`,
[productId, image.url, image.color_id || null, image.size_id || null]
)
);
const insertedImagesResults = await Promise.all(imagesInsertPromises);
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
}));
}
// Insert colors and sizes
let insertedColors: number[] = [];
let insertedSizes: number[] = [];
if (productData.has_color && productData.colors && productData.colors.length > 0) {
for (const color of productData.colors) {
// Adjust color price if necessary
let adjustedColorPrice: number = color.price;
if (adjustedColorPrice < 1000) {
adjustedColorPrice = parseFloat((adjustedColorPrice * 1000).toFixed(2));
}
// Insert or Update color
let colorId: number;
if (color.id) {
// Update existing color
await query(
`
UPDATE colors
SET
name = $1,
price = $2,
qty = $3,
sold = $4,
has_size = $5
WHERE id = $6
`,
[
color.name,
adjustedColorPrice,
color.qty,
color.sold || 0,
color.has_size,
color.id
]
);
colorId = color.id;
} else {
// Insert new color
const colorResult = await query(
`
INSERT INTO colors
(product_id, name, price, qty, sold, has_size)
VALUES
($1, $2, $3, $4, 0, $5)
RETURNING id
`,
[productId, color.name, adjustedColorPrice, color.qty, color.has_size]
);
colorId = colorResult.rows[0].id;
insertedColors.push(colorId);
}
// Insert color images
if (color.images.length > 0) {
const colorImagesInsertPromises = color.images.map((image: ImageInput) =>
query(
`
INSERT INTO images
(product_id, color_id, url, size_id)
VALUES
($1, $2, $3, $4)
RETURNING id, url, color_id, size_id
`,
[productId, colorId, image.url, image.size_id || null]
)
);
await Promise.all(colorImagesInsertPromises);
}
// Insert sizes within color
if (color.has_size && color.sizes && color.sizes.length > 0) {
for (const size of color.sizes) {
// Adjust size price if necessary
let adjustedSizePrice: number = size.price;
if (adjustedSizePrice < 1000) {
adjustedSizePrice = parseFloat((adjustedSizePrice * 1000).toFixed(2));
}
// Insert or Update size
let sizeId: number;
if (size.id) {
// Update existing size
await query(
`
UPDATE sizes
SET
name = $1,
price = $2,
qty = $3,
sold = $4,
color_id = $5
WHERE id = $6
`,
[
size.name,
adjustedSizePrice,
size.qty,
size.sold || 0,
colorId,
size.id
]
);
sizeId = size.id;
} else {
// Insert new 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]
);
sizeId = sizeResult.rows[0].id;
insertedSizes.push(sizeId);
}
// Insert size images
if (size.images.length > 0) {
const sizeImagesInsertPromises = size.images.map((image: ImageInput) =>
query(
`
INSERT INTO images
(product_id, color_id, size_id, url)
VALUES
($1, $2, $3, $4)
RETURNING id, url, color_id, size_id
`,
[productId, colorId, sizeId, image.url]
)
);
await Promise.all(sizeImagesInsertPromises);
}
}
}
}
} else if (productData.has_size && productData.sizes && productData.sizes.length > 0) {
for (const size of productData.sizes) {
// Adjust size price if necessary
let adjustedSizePrice: number = size.price;
if (adjustedSizePrice < 1000) {
adjustedSizePrice = parseFloat((adjustedSizePrice * 1000).toFixed(2));
}
// Insert or Update size
let sizeId: number;
if (size.id) {
// Update existing size
await query(
`
UPDATE sizes
SET
name = $1,
price = $2,
qty = $3,
sold = $4
WHERE id = $5
`,
[
size.name,
adjustedSizePrice,
size.qty,
size.sold || 0,
size.id
]
);
sizeId = size.id;
} else {
// Insert new 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]
);
sizeId = sizeResult.rows[0].id;
insertedSizes.push(sizeId);
}
// Insert size images
if (size.images.length > 0) {
const sizeImagesInsertPromises = size.images.map((image: ImageInput) =>
query(
`
INSERT INTO images
(product_id, size_id, url)
VALUES
($1, $2, $3)
RETURNING id, url, color_id, size_id
`,
[productId, sizeId, image.url]
)
);
await Promise.all(sizeImagesInsertPromises);
}
}
}
// Fetch and populate categories with details
const categories = await fetchCategoryDetails(productData.category_ids);
// Construct the updated product object as it would appear in the cache
const updatedProduct: 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: adjustedProductPrice,
qty: productData.qty,
sold: 0, // Assuming sold remains unchanged; adjust if necessary
created_at: result.rows[0].created_at.toISOString(),
updated_at: new Date().toISOString(),
categories: categories,
colors: productData.has_color && productData.colors
? productData.colors.map((color, index) => ({
id: color.id || insertedColors[index],
name: color.name,
price: color.price,
qty: color.qty,
sold: color.sold || 0,
has_size: color.has_size,
sizes: color.has_size && color.sizes
? color.sizes.map((size, sIndex) => ({
id: size.id || insertedSizes[sIndex],
name: size.name,
price: size.price,
qty: size.qty,
sold: size.sold || 0,
color_id: color.id || insertedColors[index],
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: size.id || insertedSizes[index],
name: size.name,
price: size.price,
qty: size.qty,
sold: size.sold || 0,
color_id: null,
images: size.images.map(img => img.url)
}))
: [],
images: insertedImages
};
// Update the cache
updateProductInCache(updatedProduct);
await query('COMMIT');
res.json({ message: 'Product updated successfully', product: updatedProduct });
} catch (error) {
await query('ROLLBACK');
console.error('Error updating product:', error);
res.status(500).json({ error: 'Internal server error' });
}
};