Certainly! To add a new sold column to your products, sizes, and colors tables and integrate this change into your Express backend, follow the steps below:
- Alter the PostgreSQL Tables to Add the
sold Column
- Update Backend Code to Handle the
sold Column
1. Alter the PostgreSQL Tables to Add the sold Column
First, you'll need to add the sold column to each of the three tables. This column will track the number of units sold for each product, size, and color. We'll set the default value to 0 to ensure existing records are initialized correctly.
SQL Queries to Alter Tables
-- Add 'sold' column to the 'products' table
ALTER TABLE products
ADD COLUMN sold INTEGER NOT NULL DEFAULT 0;
-- Add 'sold' column to the 'sizes' table
ALTER TABLE sizes
ADD COLUMN sold INTEGER NOT NULL DEFAULT 0;
-- Add 'sold' column to the 'colors' table
ALTER TABLE colors
ADD COLUMN sold INTEGER NOT NULL DEFAULT 0;
Execution Steps:
-
Using psql CLI:
psql -U your_username -d your_database -f alter_tables.sql
(Assuming you saved the above SQL statements in a file named alter_tables.sql.)
-
Using a Database Management Tool:
- Open your preferred PostgreSQL client (e.g., pgAdmin, DBeaver).
- Execute each
ALTER TABLE statement separately or all at once.
2. Update Backend Code to Handle the sold Column
After updating the database schema, you'll need to adjust your backend code to incorporate the sold column. This involves updating SQL queries to select, insert, and update the sold field appropriately.
Overview of Changes:
-
Fetching Data (getProducts & getProductById):
- Include the
sold column in SELECT statements.
- Ensure the
sold field is included in the JSON response.
-
Creating Data (createProduct):
- Initialize the
sold field to 0 on creation.
- Ensure
sold is handled for products, colors, and sizes.
-
Updating Data (updateProduct):
- Allow updating the
sold field if necessary.
- Ensure updates do not unintentionally overwrite the
sold count.
-
Optional: Handling Sales
- Implement endpoints or logic to increment the
sold count when a sale occurs.
Below are the detailed modifications for each relevant backend function.
2.1. getProducts Function
Current Function:
export const getProducts = async (req: Request, res: Response) => {
// ... existing code
const productQuery = `
WITH filtered_products AS (
SELECT p.*,
sc.id AS subcategory_id, sc.name AS subcategory_name,
c.id AS main_category_id, c.name AS main_category_name,
COUNT(*) OVER() AS total_count
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
${whereClause}
ORDER BY
CASE
WHEN $${queryParams.length - 2} != '' THEN
CASE
WHEN LOWER(p.name) LIKE LOWER($${queryParams.length - 2} || '%') THEN 1
WHEN LOWER(p.name) LIKE '%' || LOWER($${queryParams.length - 2}) || '%' THEN 2
ELSE 3
END
ELSE 0
END,
p.created_at DESC
)
SELECT
fp.*,
-- ... existing JSON aggregations
FROM filtered_products fp
LIMIT $${queryParams.length - 1}::integer OFFSET $${queryParams.length}::integer
`;
// ... existing code to map products
};
Modified Function:
-
Include p.sold in the SELECT Statement:
- Add
p.sold to the main SELECT inside filtered_products.
-
Include sold in JSON Response:
- Ensure the
sold field is mapped to the product object.
Modified SQL Query Snippet:
SELECT p.*,
sc.id AS subcategory_id, sc.name AS subcategory_name,
c.id AS main_category_id, c.name AS main_category_name,
p.sold, -- <-- Add this line
COUNT(*) OVER() AS total_count
FROM products p
-- ... rest of the query
Modified Mapping in JavaScript:
const products = productResult.rows.map(product => ({
id: product.id,
name: product.name,
description: product.description,
brand_id: product.brand_id,
has_color: product.has_color,
has_size: product.has_size,
product_type: product.product_type,
price: product.price,
qty: product.qty,
sold: product.sold, // <-- Add this line
created_at: product.created_at,
updated_at: product.updated_at,
// ... rest of the fields
}));
2.2. getProductById Function
Current Function:
export const getProductById = async (req: Request, res: Response) => {
// ... existing code
const productQuery = `
SELECT
p.id AS product_id,
p.name AS product_name,
p.description,
-- ... existing fields
FROM products p
-- ... rest of the query
`;
// ... existing code to process and map the product
};
Modified Function:
-
Include p.sold in the SELECT Statement:
- Add
p.sold to the main SELECT.
-
Include sold in Related Entities:
- Include
sold for colors and sizes.
Modified SQL Query Snippet:
SELECT
p.id AS product_id,
p.name AS product_name,
p.description,
p.sold, -- <-- Add this line
-- ... existing fields
cl.sold AS color_sold, -- <-- Add this line
s.sold AS size_sold, -- <-- Add this line
-- ... existing fields
FROM products p
LEFT JOIN colors cl ON p.id = cl.product_id
LEFT JOIN sizes s ON (p.id = s.product_id AND (cl.id = s.color_id OR s.color_id IS NULL))
-- ... rest of the query
Modified Mapping in JavaScript:
// When initializing the product object
const product = {
id: result.rows[0].product_id,
name: result.rows[0].product_name,
description: result.rows[0].description,
sold: result.rows[0].sold, // <-- Add this line
// ... rest of the fields
};
// When adding colors
if (row.color_id && !product.colors.some(c => c.id === row.color_id)) {
product.colors.push({
id: row.color_id,
name: row.color_name,
price: row.color_price,
qty: row.color_qty,
sold: row.color_sold, // <-- Add this line
images: [],
sizes: []
});
}
// When adding sizes
if (row.size_id && !product.sizes.some(s => s.id === row.size_id)) {
const newSize = {
id: row.size_id,
name: row.size_name,
price: row.size_price,
qty: row.size_qty,
sold: row.size_sold, // <-- Add this line
color_id: row.color_id,
images: []
};
product.sizes.push(newSize);
// ... rest of the code
}
2.3. createProduct Function
Current Function:
export const createProduct = async (req: Request, res: Response) => {
try {
await query('BEGIN');
const productData = req.body;
if (productData.price < 1000) {
productData.price *= 1000;
}
const productResult = await query(
'INSERT INTO products (name, description, brand_id, has_color, has_size, product_type, price, qty) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id',
[productData.name, productData.description, productData.brand_id, productData.hasColor, productData.hasSize, productData.product_type, productData.price, productData.qty]
);
const productId = productResult.rows[0].id;
// ... rest of the code
} catch (error) {
// ... error handling
}
};
Modified Function:
-
Initialize sold to 0 When Inserting:
- Add
sold to the INSERT statement with a default value.
-
Handle sold for Colors and Sizes:
- Ensure
sold is initialized to 0 when inserting colors and sizes.
Modified SQL Queries:
// Insert into 'products' with 'sold' initialized to 0
const productResult = await query(
'INSERT INTO products (name, description, brand_id, has_color, has_size, product_type, price, qty, sold) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 0) RETURNING id',
[productData.name, productData.description, productData.brand_id, productData.hasColor, productData.hasSize, productData.product_type, productData.price, productData.qty]
);
// Insert into 'colors' with 'sold' initialized to 0
const colorResult = await query(
'INSERT INTO colors (product_id, name, has_size, price, qty, sold) VALUES ($1, $2, $3, $4, $5, 0) RETURNING id',
[productId, color.name, color.hasSize, color.price, color.qty]
);
// Insert into 'sizes' with 'sold' initialized to 0
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, size.price, size.qty]
);
Modified Code Snippets:
// Insert into 'products' with 'sold'
const productResult = await query(
'INSERT INTO products (name, description, brand_id, has_color, has_size, product_type, price, qty, sold) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 0) RETURNING id',
[productData.name, productData.description, productData.brand_id, productData.hasColor, productData.hasSize, productData.product_type, productData.price, productData.qty]
);
// ... rest of the code
// Insert into 'colors' with 'sold'
const colorResult = await query(
'INSERT INTO colors (product_id, name, has_size, price, qty, sold) VALUES ($1, $2, $3, $4, $5, 0) RETURNING id',
[productId, color.name, color.hasSize, color.price, color.qty]
);
// ... rest of the code
// Insert into 'sizes' with 'sold'
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, size.price, size.qty]
);
2.4. updateProduct Function
Current Function:
export const updateProduct = async (req: Request, res: Response) => {
const { id } = req.params;
const productData = req.body;
try {
await query('BEGIN');
// ... existing update logic
} catch (error) {
// ... error handling
}
};
Modified Function:
-
Include sold in Update Statements (Optional):
- If you want to allow updating the
sold count via the API, include it in the UPDATE statements.
- Note: If
sold should only be modified through sales logic, avoid exposing it for manual updates.
-
Prevent Unintentional Overwrite:
- If not allowing manual updates, ensure
sold is not altered unintentionally during updates.
Option 1: Allowing Manual Updates to sold
Modified SQL Update Statement:
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,
sold = $9, -- <-- Add this line
updated_at = CURRENT_TIMESTAMP
WHERE id = $10
RETURNING *`,
[
productData.name,
productData.description,
productData.brand_id,
productData.hasColor,
productData.hasSize,
productData.product_type,
productData.price,
productData.qty,
productData.sold, // <-- Add this line
id
]
);
Handling Colors and Sizes:
// Update existing color with 'sold'
await query(
`UPDATE colors
SET name = $1,
has_size = $2,
price = $3,
qty = $4,
sold = $5
WHERE id = $6`,
[color.name, color.hasSize, color.price, color.qty, color.sold, color.id]
);
// Update existing size with 'sold'
await query(
`UPDATE sizes
SET name = $1,
price = $2,
qty = $3,
sold = $4
WHERE id = $5`,
[size.name, size.price, size.qty, size.sold, size.id]
);
Option 2: Manage sold Internally (Recommended)
If the sold count should only change as a result of sales transactions, avoid allowing manual updates via the updateProduct API. Instead, implement dedicated endpoints or services to handle sales and increment the sold count accordingly.
Example: Increment sold When a Sale Occurs
export const incrementSold = async (req: Request, res: Response) => {
const { productId, colorId, sizeId, quantity } = req.body; // Adjust based on your sales data structure
try {
await query('BEGIN');
// Increment sold for the product
await query(
'UPDATE products SET sold = sold + $1 WHERE id = $2',
[quantity, productId]
);
if (colorId) {
// Increment sold for the color
await query(
'UPDATE colors SET sold = sold + $1 WHERE id = $2',
[quantity, colorId]
);
}
if (sizeId) {
// Increment sold for the size
await query(
'UPDATE sizes SET sold = sold + $1 WHERE id = $2',
[quantity, sizeId]
);
}
await query('COMMIT');
res.json({ message: 'Sold count incremented successfully' });
} catch (error) {
await query('ROLLBACK');
console.error('Error incrementing sold count:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
Note: Implement appropriate validation and error handling as needed.
2.5. deleteProduct Function
Ensure that when deleting products, related sold data does not cause inconsistencies. Typically, deleting a product will remove its associated sold counts automatically, but ensure referential integrity.
No changes are strictly necessary for the sold column in the deleteProduct function, as deleting the product and its related entities will remove the sold counts. However, ensure that all related deletions are handled within the transaction.
Summary of Changes
-
Database:
- Added a
sold column to the products, colors, and sizes tables with a default value of 0.
-
Backend:
- Fetching Data: Included the
sold field in all relevant SELECT queries and ensured it's part of the JSON responses.
- Creating Data: Initialized the
sold field to 0 when inserting new records.
- Updating Data: Decided whether to allow manual updates to the
sold count or manage it internally via dedicated endpoints.
- Optional Sales Handling: Implemented an example endpoint to increment the
sold count upon a sale.
Complete Example: Updated Backend Code Snippets
Below are complete examples of the modified backend functions with the sold column integrated.
Updated getProducts Function
export const getProducts = async (req: Request, res: Response) => {
try {
const page = parseInt(req.query.page as string) || 1;
const limit = 10;
const offset = (page - 1) * limit;
const search = (req.query.search as string || '').toLowerCase();
const categoryId = req.query.c as string;
const subcategoryId = req.query.sc as string;
const brandId = req.query.b as string;
const conditions = [];
const queryParams: any[] = [];
if (search) {
const searchWords = search.split(/\s+/).filter(Boolean);
const searchConditions = searchWords.map((word) => {
queryParams.push(`${word}%`, `%${word}%`);
return `(LOWER(p.name) LIKE $${queryParams.length - 1} OR LOWER(p.name) LIKE $${queryParams.length})`;
});
conditions.push(`(${searchConditions.join(' OR ')})`);
}
if (categoryId) {
queryParams.push(categoryId);
conditions.push(`(c.id = $${queryParams.length} OR EXISTS (
SELECT 1 FROM subcategories sub
WHERE sub.category_id = $${queryParams.length}
AND (sub.id = sc.id OR sub.id = p.brand_id)
))`);
}
if (subcategoryId) {
queryParams.push(subcategoryId);
conditions.push(`(sc.id = $${queryParams.length} OR p.brand_id = $${queryParams.length})`);
}
if (brandId) {
queryParams.push(brandId);
conditions.push(`p.brand_id = $${queryParams.length}`);
}
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
// Add search, limit, and offset to queryParams
queryParams.push(search, limit, offset);
const productQuery = `
WITH filtered_products AS (
SELECT p.*,
sc.id AS subcategory_id, sc.name AS subcategory_name,
c.id AS main_category_id, c.name AS main_category_name,
p.sold, -- Include sold
COUNT(*) OVER() AS total_count
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
${whereClause}
ORDER BY
CASE
WHEN $${queryParams.length - 2} != '' THEN
CASE
WHEN LOWER(p.name) LIKE LOWER($${queryParams.length - 2} || '%') THEN 1
WHEN LOWER(p.name) LIKE '%' || LOWER($${queryParams.length - 2}) || '%' THEN 2
ELSE 3
END
ELSE 0
END,
p.created_at DESC
)
SELECT
fp.*,
-- ... existing JSON aggregations
FROM filtered_products fp
LIMIT $${queryParams.length - 1}::integer OFFSET $${queryParams.length}::integer
`;
const productResult = await query(productQuery, queryParams);
const totalProducts = parseInt(productResult.rows[0]?.total_count || '0');
const totalPages = Math.ceil(totalProducts / limit);
const products = productResult.rows.map(product => ({
id: product.id,
name: product.name,
description: product.description,
brand_id: product.brand_id,
has_color: product.has_color,
has_size: product.has_size,
product_type: product.product_type,
price: product.price,
qty: product.qty,
sold: product.sold, // Include sold
created_at: product.created_at,
updated_at: product.updated_at,
categories: [
{
id: product.subcategory_id,
name: product.subcategory_name,
main_category_id: product.main_category_id,
main_category_name: product.main_category_name
}
],
colors: product.colors || [],
sizes: product.sizes || [],
images: [
...(product.images || []),
...(product.colors || []).flatMap((c: { images: any; }) => c.images || []),
...(product.sizes || []).flatMap((s: { images: any; }) => s.images || [])
]
}));
const result = {
products,
pagination: {
currentPage: page,
totalPages,
totalProducts,
limit
}
};
res.json(result);
} catch (error) {
console.error('Error fetching products:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
Updated getProductById Function
export const getProductById = async (req: Request, res: Response) => {
const { id } = req.params;
try {
const productQuery = `
SELECT
p.id AS product_id,
p.name AS product_name,
p.description,
p.sold, -- Include sold
p.brand_id,
p.has_color,
p.has_size,
p.product_type,
p.price AS product_price,
p.qty AS product_qty,
p.created_at,
p.updated_at,
pc.category_id,
sc.name AS category_name,
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, -- Include sold
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, -- Include sold
i.id AS image_id,
i.url AS image_url
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 colors cl ON p.id = cl.product_id
LEFT JOIN sizes s ON (p.id = s.product_id AND (cl.id = s.color_id OR s.color_id IS NULL))
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))
WHERE p.id = $1
ORDER BY pc.category_id, cl.id, s.id, i.id
`;
const result = await query(productQuery, [id]);
if (result.rows.length === 0) {
return res.status(404).json({ error: 'Product not found' });
}
// Process the result to group related data
const product = {
id: result.rows[0].product_id,
name: result.rows[0].product_name,
description: result.rows[0].description,
sold: result.rows[0].sold, // Include sold
brand_id: result.rows[0].brand_id,
has_color: result.rows[0].has_color,
has_size: result.rows[0].has_size,
product_type: result.rows[0].product_type,
price: result.rows[0].product_price,
qty: result.rows[0].product_qty,
created_at: result.rows[0].created_at,
updated_at: result.rows[0].updated_at,
categories: [],
colors: [],
sizes: [],
images: []
};
for (const row of result.rows) {
if (row.category_id && !product.categories.some(c => c.id === row.category_id)) {
product.categories.push({
id: row.category_id,
name: row.category_name
});
}
// Add color if not already added
if (row.color_id && !product.colors.some(c => c.id === row.color_id)) {
product.colors.push({
id: row.color_id,
name: row.color_name,
price: row.color_price,
qty: row.color_qty,
sold: row.color_sold, // Include sold
images: [],
sizes: []
});
}
// Add size if not already added
if (row.size_id && !product.sizes.some(s => s.id === row.size_id)) {
const newSize = {
id: row.size_id,
name: row.size_name,
price: row.size_price,
qty: row.size_qty,
sold: row.size_sold, // Include sold
color_id: row.color_id,
images: []
};
product.sizes.push(newSize);
// Add size to the corresponding color
if (row.color_id) {
const color = product.colors.find(c => c.id === row.color_id);
if (color && !color.sizes.some((s: { id: any; }) => s.id === row.size_id)) {
color.sizes.push(newSize);
}
}
}
// Add image to the product, and to the appropriate color or size
if (row.image_id && !product.images.some(i => i.id === row.image_id)) {
const newImage = {
id: row.image_id,
url: row.image_url,
color_id: row.color_id,
size_id: row.size_id
};
product.images.push(newImage);
if (row.color_id) {
const color = product.colors.find(c => c.id === row.color_id);
if (color && !color.images.includes(row.image_url)) {
color.images.push(row.image_url);
}
}
if (row.size_id) {
const size = product.sizes.find(s => s.id === row.size_id);
if (size && !size.images.includes(row.image_url)) {
size.images.push(row.image_url);
}
}
}
}
res.json({ product });
} catch (error) {
console.error('Error fetching product by ID:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
Updated createProduct Function
// Create a new product
export const createProduct = async (req: Request, res: Response) => {
try {
await query('BEGIN');
const productData = req.body;
if (productData.price < 1000) {
productData.price *= 1000;
}
// Insert into 'products' with 'sold' initialized to 0
const productResult = await query(
'INSERT INTO products (name, description, brand_id, has_color, has_size, product_type, price, qty, sold) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 0) RETURNING id',
[productData.name, productData.description, productData.brand_id, productData.hasColor, productData.hasSize, productData.product_type, productData.price, productData.qty]
);
const productId = productResult.rows[0].id;
// Insert category associations
for (const categoryId of productData.category_ids) {
await query(
'INSERT INTO product_categories (product_id, category_id) VALUES ($1, $2)',
[productId, categoryId]
);
}
// Insert images
for (const imageUrl of productData.images) {
await query(
'INSERT INTO images (product_id, url) VALUES ($1, $2)',
[productId, imageUrl]
);
}
// Handle colors and sizes based on product type
if (productData.hasColor) {
for (const color of productData.colors) {
// Adjust color price if less than 1000
if (color.price < 1000) {
color.price *= 1000;
}
// Insert into 'colors' with 'sold' initialized to 0
const colorResult = await query(
'INSERT INTO colors (product_id, name, has_size, price, qty, sold) VALUES ($1, $2, $3, $4, $5, 0) RETURNING id',
[productId, color.name, color.hasSize, color.price, color.qty]
);
const colorId = colorResult.rows[0].id;
// Insert color images
for (const imageUrl of color.images) {
await query(
'INSERT INTO images (product_id, color_id, url) VALUES ($1, $2, $3)',
[productId, colorId, imageUrl]
);
}
if (color.hasSize) {
for (const size of color.sizes) {
// Adjust size price if less than 1000
if (size.price < 1000) {
size.price *= 1000;
}
// Insert into 'sizes' with 'sold' initialized to 0
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, size.price, size.qty]
);
const sizeId = sizeResult.rows[0].id;
// Insert size images
for (const imageUrl of size.images) {
await query(
'INSERT INTO images (product_id, color_id, size_id, url) VALUES ($1, $2, $3, $4)',
[productId, colorId, sizeId, imageUrl]
);
}
}
}
}
} else if (productData.hasSize) {
for (const size of productData.sizes) {
// Adjust size price if less than 1000
if (size.price < 1000) {
size.price *= 1000;
}
// Insert into 'sizes' with 'sold' initialized to 0
const sizeResult = await query(
'INSERT INTO sizes (product_id, name, price, qty, sold) VALUES ($1, $2, $3, $4, 0) RETURNING id',
[productId, size.name, size.price, size.qty]
);
const sizeId = sizeResult.rows[0].id;
// Insert size images
for (const imageUrl of size.images) {
await query(
'INSERT INTO images (product_id, size_id, url) VALUES ($1, $2, $3)',
[productId, sizeId, imageUrl]
);
}
}
}
await query('COMMIT');
res.status(201).json({ message: 'Product created successfully', productId });
} catch (error) {
await query('ROLLBACK');
console.error('Error creating product:', error);
res.status(500).json({ error: 'Internal server error' });
} finally {
}
};
Updated updateProduct Function
Option 2 (Recommended): Manage sold Internally
// Update a product without allowing manual 'sold' updates
export const updateProduct = async (req: Request, res: Response) => {
const { id } = req.params;
const productData = req.body;
try {
await query('BEGIN');
// Adjust main product price if less than 1000
if (productData.price < 1000) {
productData.price *= 1000;
}
// Update main product details without altering 'sold'
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.hasColor,
productData.hasSize,
productData.product_type,
productData.price,
productData.qty,
id
]
);
if (result.rows.length === 0) {
await query('ROLLBACK');
return res.status(404).json({ error: 'Product not found' });
}
// ... existing logic to handle categories, images, colors, and sizes
// Example: Do not update 'sold' fields here to manage them internally
await query('COMMIT');
res.json({ message: 'Product updated successfully', product: result.rows[0] });
} catch (error) {
await query('ROLLBACK');
console.error('Error updating product:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
3. Optional: Implementing Sales Logic to Increment sold Counts
To fully integrate the sold functionality, you should implement logic that increments the sold count whenever a product, size, or color is sold. This typically occurs during order processing. Here's an example of how you might implement this.
Example: Order Processing Endpoint
export const processOrder = async (req: Request, res: Response) => {
const { items } = req.body; // items should include productId, colorId (optional), sizeId (optional), quantity
try {
await query('BEGIN');
for (const item of items) {
const { productId, colorId, sizeId, quantity } = item;
// Validate input as needed
// Decrement stock quantities
if (sizeId) {
await query(
'UPDATE sizes SET qty = qty - $1, sold = sold + $1 WHERE id = $2 AND qty >= $1',
[quantity, sizeId]
);
} else if (colorId) {
await query(
'UPDATE colors SET qty = qty - $1, sold = sold + $1 WHERE id = $2 AND qty >= $1',
[quantity, colorId]
);
} else {
await query(
'UPDATE products SET qty = qty - $1, sold = sold + $1 WHERE id = $2 AND qty >= $1',
[quantity, productId]
);
}
// Optionally, insert into an orders table, etc.
}
await query('COMMIT');
res.json({ message: 'Order processed successfully' });
} catch (error) {
await query('ROLLBACK');
console.error('Error processing order:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
Notes:
-
Validation: Ensure that the stock quantities are sufficient before decrementing. The above queries include AND qty >= $1 to prevent negative stock, but you might want to handle cases where the stock is insufficient more gracefully.
-
Atomicity: Using transactions (BEGIN/COMMIT/ROLLBACK) ensures that all updates occur atomically.
-
Error Handling: Properly handle errors, such as insufficient stock or invalid IDs.
Conclusion
By following the above steps, you have successfully:
-
Updated the Database Schema: Added a sold column to products, colors, and sizes tables with appropriate default values.
-
Modified Backend Logic: Integrated the sold column into your backend Express application, ensuring it's handled during data retrieval, creation, and updates.
-
(Optional) Implemented Sales Handling: Provided an example of how to manage sales transactions to increment the sold counts appropriately.
Ensure thorough testing after making these changes to verify that the sold counts are accurately tracked and that no existing functionality is disrupted.
Remember to backup your database before performing schema alterations and thoroughly test all changes in a development environment before deploying to production.