Even though when type is color_size and colors has sizes, the sizes inside colors is empty...
for example the object in handle submit is like this:
{
"name": "test",
"description": "test",
"brand_id": 73,
"has_color": true,
"has_size": false,
"product_type": "color_size",
"category_ids": [
178
],
"colors": [
{
"name": "red",
"images": [],
"has_size": true,
"sizes": [
{
"name": "20ml",
"price": 20,
"qty": 20,
"images": []
}
],
"price": null,
"qty": 0
}
],
"sizes": [],
"price": null,
"qty": 0,
"images": []
}
the result in the backend is:
{"id":1207,"name":"test","description":"test","brand_id":73,"has_color":true,"has_size":false,"product_type":"color_size","price":0,"qty":0,"sold":0,"created_at":"2024-09-24T11:58:58.539Z","updated_at":"2024-09-24T11:58:58.539Z","categories":[{"id":178,"name":"Body Cleansers","main_category_id":2,"main_category_name":"Body Care"}],"colors":[{"id":45,"name":"red","price":0,"qty":0,"sold":0,"has_size":false,"sizes":[],"images":[]}],"sizes":[{"id":10,"name":"20ml","price":20000,"qty":20,"sold":0,"color_id":45,"images":[]}],"images":[]},
frontend:
"use client";
import React, { useState, useEffect } from "react";
import { X, Plus } from "lucide-react";
import { MultipartFileUploader } from "@/components/MultipartFileUploader";
import { toast } from "react-toastify";
import { getToken } from "@/app/auth";
};
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)) ;
try {
const result = await query(q, []);
const productsMap: Record<number, Product> = {};
result.rows.forEach((row: any) => {
const productId = Number(row.id);
if (!productsMap[productId]) {
productsMap[productId] = {
id: productId,
name: row.name,
description: row.description,
brand_id: Number(row.brand_id),
has_color: Boolean(row.has_color),
has_size: Boolean(row.has_size),
product_type: row.product_type,
price: Number(row.price),
qty: Number(row.qty),
sold: Number(row.sold),
created_at: new Date(row.created_at).toISOString(),
updated_at: new Date(row.updated_at).toISOString(),
categories: [],
colors: [],
sizes: [],
images: []
};
}
// Add category if not already present
if (
row.subcategory_id &&
row.subcategory_name &&
row.main_category_id &&
row.main_category_name
) {
const categoryId = Number(row.subcategory_id);
const mainCategoryId = Number(row.main_category_id);
const existingCategory = productsMap[productId].categories.find(cat => cat.id === categoryId);
if (!existingCategory) {
productsMap[productId].categories.push({
id: categoryId,
name: row.subcategory_name,
main_category_id: mainCategoryId,
main_category_name: row.main_category_name,
});
}
}
// Add color if not already present
if (row.color_id && row.color_name && row.has_size !== undefined) {
const colorId = Number(row.color_id);
const existingColor = productsMap[productId].colors.find(color => color.id === colorId);
if (!existingColor) {
productsMap[productId].colors.push({
id: colorId,
name: row.color_name,
price: Number(row.color_price),
qty: Number(row.color_qty),
sold: Number(row.color_sold),
has_size: Boolean(row.has_size),
sizes: [],
images: []
});
}
}
// Add size if not already present
if (row.size_id && row.size_name) {
const sizeId = Number(row.size_id);
const existingSize = productsMap[productId].sizes.find(size => size.id === sizeId);
if (!existingSize) {
productsMap[productId].sizes.push({
id: sizeId,
name: row.size_name,
price: Number(row.size_price),
qty: Number(row.size_qty),
sold: Number(row.size_sold),
color_id: row.color_id ? Number(row.color_id) : null,
images: []
});
}
}
// Add image if not already present
if (row.image_id && row.image_url) {
const imageId = Number(row.image_id);
const existingImage = productsMap[productId].images.find(img => img.id === imageId);
if (!existingImage) {
productsMap[productId].images.push({
id: imageId,
url: row.image_url,
color_id: row.image_color_id ? Number(row.image_color_id) : null,
size_id: row.image_size_id ? Number(row.image_size_id) : null
});
}
// Associate image with color if applicable
if (row.image_color_id) {
const color = productsMap[productId].colors.find(c => c.id === Number(row.image_color_id));
if (color && !color.images.includes(row.image_url)) {
color.images.push(row.image_url);
}
}
// Associate image with size if applicable
if (row.image_size_id) {
const size = productsMap[productId].sizes.find(s => s.id === Number(row.image_size_id));
if (size && !size.images.includes(row.image_url)) {
size.images.push(row.image_url);
}
}
}
});
const allProducts = Object.values(productsMap);
// Calculate min and max prices across all products
let minPrice = Infinity;
let maxPrice = -Infinity;
allProducts.forEach(product => {
// Product price
if (product.price < minPrice) minPrice = product.price;
if (product.price > maxPrice) maxPrice = product.price;
// Prices from colors and their sizes
product.colors.forEach(color => {
if (color.price < minPrice) minPrice = color.price;
if (color.price > maxPrice) maxPrice = color.price;
color.sizes.forEach(size => {
if (size.price < minPrice) minPrice = size.price;
if (size.price > maxPrice) maxPrice = size.price;
});
});
// Prices from standalone sizes
product.sizes.forEach(size => {
if (size.price < minPrice) minPrice = size.price;
if (size.price > maxPrice) maxPrice = size.price;
});
});
// Fallback in case no prices are present
if (minPrice === Infinity) minPrice = 0;
if (maxPrice === -Infinity) maxPrice = 0;
// Cache the data with a consistent key
const cacheData: CacheData = { allProducts, minPrice, maxPrice };
productCache.set('allProducts', cacheData);
console.log(`Cached ${allProducts.length} products with minPrice: ${minPrice} and maxPrice: ${maxPrice}.`);
return cacheData;
} catch (error) {
console.error('Error loading products from DB:', error);
throw error; // Propagate error to be handled by caller
}
};
/**
Fetches all brands from the database and caches them.
@returns {Promise} A promise that resolves to the cached brand data.
*/
const loadAndCacheAllBrands = async (): Promise => {
const q = SELECT s.*, c.name as category_name FROM subcategories s JOIN categories c ON s.category_id = c.id AND c.is_brand ORDER BY c.name, s.name ;
if (!cacheData) {
// Cache miss: Load from DB and cache
cacheData = await loadAndCacheAllProducts();
console.log('Loaded products from database and cached them.');
} else {
console.log('Loaded products from cache.');
}
const { allProducts, minPrice, maxPrice } = cacheData;
// Log total products before any filtering
console.log(`Total products before filtering: ${allProducts.length}`);
// Extract and sanitize query parameters
let {
search = '',
c,
sc,
b,
minPriceA = '0',
maxPriceA = '',
availability = 'all',
sortBy = '',
page = '1',
itemsPerPage = '15',
} = req.query;
// Parse numerical values
const pageNum = parseInt(page as string, 10) || 1;
const itemsPerPageNum = parseInt(itemsPerPage as string, 10) || 15;
const minPriceANum = parseFloat(minPriceA as string) || 0;
let maxPriceANum = maxPriceA ? parseFloat(maxPriceA as string) : Infinity;
// If maxPriceA is less than minPriceA, reset to Infinity
if (!isNaN(maxPriceANum) && maxPriceANum < minPriceANum) {
console.warn('Provided maxPriceA is less than minPriceA. Resetting maxPriceANum to Infinity.');
maxPriceANum = Infinity;
} else if (isNaN(maxPriceANum)) {
maxPriceANum = Infinity;
}
// Parse c, sc, b as numbers if present
const cNum = c ? parseInt(c as string, 10) : undefined;
const scNum = sc ? parseInt(sc as string, 10) : undefined;
const bNum = b ? parseInt(b as string, 10) : undefined;
// Initialize brand-related variables if 'b' is provided
let allBrands: Brand[] = [];
if (bNum !== undefined && !isNaN(bNum)) {
// Retrieve cached brands
let brandsCacheData: BrandsCacheData | undefined = brandsCache.get('allBrands');
if (!brandsCacheData) {
// Cache miss: Load from DB and cache
brandsCacheData = await loadAndCacheAllBrands();
console.log('Loaded brands from database and cached them.');
} else {
console.log('Loaded brands from cache.');
}
console.log(brandsCacheData)
allBrands = brandsCacheData.allBrands;
// Check if 'bNum' is a valid brand ID
const isValidBrand = allBrands.some(brand => brand.category_id === bNum);
if (!isValidBrand) {
console.warn(`Brand ID ${bNum} is invalid.`);
// Return zero products since 'b' is invalid
res.json({
products: [],
total: 0,
page: pageNum,
itemsPerPage: itemsPerPageNum,
totalPages: 0,
hasMore: false,
minPrice,
maxPrice,
});
return;
}
}
// Start with all products
let filteredProducts = [...allProducts];
// Apply Search Filter
if (search && typeof search === 'string') {
const searchLower = search.toLowerCase();
const searchWords = searchLower.split(/\s+/).filter(Boolean);
filteredProducts = filteredProducts.filter(product =>
searchWords.every(word => product.name.toLowerCase().includes(word))
);
}
// Apply Category Filter (c)
if (cNum !== undefined && !isNaN(cNum)) {
filteredProducts = filteredProducts.filter(product =>
product.categories.some(cat => cat.main_category_id === cNum)
);
}
// Apply Subcategory Filter (sc)
if (scNum !== undefined && !isNaN(scNum)) {
filteredProducts = filteredProducts.filter(product =>
product.brand_id === scNum ||
product.categories.some(cat => cat.id === scNum)
);
}
// Apply Brand Filter (b)
if (bNum !== undefined && !isNaN(bNum)) {
console.log(`Applying Brand Filter: brand_id === ${bNum}`);
const preFilterCount = filteredProducts.length;
allBrands = allBrands.filter(brand => brand.category_id === bNum)
filteredProducts = filteredProducts.filter(product =>
allBrands.some(brand => brand.id === product.brand_id)
);
console.log(`Filtered from ${preFilterCount} to ${filteredProducts.length} products after applying brand filter.`);
}
// Apply Price Range Filter
if (minPriceANum > 0 || maxPriceANum < Infinity) {
filteredProducts = filteredProducts.filter(product => {
const productPrices = product.sizes.map(size => size.price);
// If product has no sizes, exclude it
if (productPrices.length === 0) return false;
const productMinPrice = Math.min(...productPrices);
const productMaxPrice = Math.max(...productPrices);
return productMinPrice >= minPriceANum && productMaxPrice <= maxPriceANum;
});
}
// Apply Availability Filter
if (availability === 'in_stock') {
filteredProducts = filteredProducts.filter(product =>
product.sizes.some(size => size.qty > 0)
);
} else if (availability === 'out_of_stock') {
filteredProducts = filteredProducts.filter(product =>
product.sizes.every(size => size.qty === 0)
);
}
// Log total after filtering
console.log(`Total products after filtering: ${filteredProducts.length}`);
// Apply Sorting
if (sortBy && typeof sortBy === 'string') {
switch (sortBy) {
case 'Price: Low to High':
filteredProducts.sort((a, b) => {
const aMin = Math.min(...a.sizes.map(s => s.price));
const bMin = Math.min(...b.sizes.map(s => s.price));
return aMin - bMin;
});
break;
case 'Price: High to Low':
filteredProducts.sort((a, b) => {
const aMax = Math.max(...a.sizes.map(s => s.price));
const bMax = Math.max(...b.sizes.map(s => s.price));
return bMax - aMax;
});
break;
case 'Name: A to Z':
filteredProducts.sort((a, b) => a.name.localeCompare(b.name));
break;
case 'Name: Z to A':
filteredProducts.sort((a, b) => b.name.localeCompare(a.name));
break;
case 'Best Selling':
filteredProducts.sort((a, b) => b.sold - a.sold);
break;
case 'Newest Arrivals':
filteredProducts.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
break;
default:
// If sortBy parameter doesn't match any case, do not sort
break;
}
}
// Apply Pagination
const totalFilteredProducts = filteredProducts.length;
const totalPages = Math.ceil(totalFilteredProducts / itemsPerPageNum);
const startIdx = (pageNum - 1) * itemsPerPageNum;
const endIdx = startIdx + itemsPerPageNum;
const paginatedProducts = filteredProducts.slice(startIdx, endIdx);
// Construct Response
const response = {
products: paginatedProducts,
total: totalFilteredProducts,
page: pageNum,
itemsPerPage: itemsPerPageNum,
totalPages,
hasMore: endIdx < totalFilteredProducts,
minPrice, // Global minPrice across all products
maxPrice, // Global maxPrice across all products
};
// Send Response
res.json(response);
} catch (error) {
console.error('Error fetching products:', error);
res.status(500).json({ error: 'Internal server error' });
} finally {
// Optional: Any cleanup operations can be performed here
// For example, monitoring memory usage or logging request completion
}
};
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.brand_id, p.has_color, p.has_size, p.product_type, p.price AS product_price, p.qty AS product_qty, p.sold AS product_sold, 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, 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, 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
let product: {
sold: any;
has_size: any;
images: any[];
description: any;
created_at: any;
colors: any[];
brand_id: any;
has_color: any;
product_type: any;
updated_at: any;
sizes: any[];
price: any;
qty: any;
name: any;
id: number;
categories: any[]
};
product = {
id: result.rows[0].product_id,
name: result.rows[0].product_name,
description: result.rows[0].description,
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,
sold: result.rows[0].product_sold,
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,
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,
color_id: row.color_id,
// @ts-ignore
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);
}
}
}
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' });
}
if (isNaN(productId)) {
return res.status(400).json({ error: 'Invalid product ID' });
}
try {
await query('BEGIN');
// Delete related data first
await query('DELETE FROM product_categories WHERE product_id = $1', [productId]);
await query('DELETE FROM images WHERE product_id = $1', [productId]);
await query('DELETE FROM sizes WHERE product_id = $1', [productId]);
await query('DELETE FROM colors WHERE product_id = $1', [productId]);
// Delete the product
const result = await query('DELETE FROM products WHERE id = $1 RETURNING *', [productId]);
if (result.rows.length === 0) {
await query('ROLLBACK');
return res.status(404).json({ error: 'Product not found' });
}
// Delete the product from the cache
deleteProductFromCache(productId);
await query('COMMIT');
res.json({ message: 'Product and related data deleted successfully' });
} catch (error) {
await query('ROLLBACK');
console.error('Error deleting product:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
It looks like you're encountering an issue where, despite submitting a product of type "color_size" with colors that have sizes, the backend isn't correctly registering the sizes within the colors. Instead, sizes are appearing as top-level entries with has_size: false in the colors. This discrepancy can cause significant inconsistencies in your data model and application behavior.
Let's break down the problem and provide a comprehensive solution:
Identifying the Root Cause
Steps to Resolve the Issue
Additional Recommendations
1. Identifying the Root Cause
Duplicate Submission in Frontend
Upon reviewing your frontend code, particularly the handleSubmit function, there's a clear duplication of the fetch POST request:
Double Submission: Submitting the form twice can lead to unintended behaviors, such as duplicate entries or conflicting data states.
Inconsistent Flags: The first submission might correctly set has_size to true for colors, while the second submission (with has_size: false at the product level) might overwrite or reset these flags, causing has_size to appear false in the backend.
Backend Handling of has_size
Even though your frontend is setting has_size: true for colors, the backend receives has_size: false. This inconsistency likely stems from the duplicated submissions where the second request might be inadvertently resetting the has_size flag.
2. Steps to Resolve the Issue
A. Remove the Duplicate POST Request
Ensure that your handleSubmit function sends the product data only once. Having two identical try-catch blocks for the POST request is unnecessary and problematic.
Removed the Second try-catch Block: Ensures the form is submitted only once.
Maintained Proper Form Resetting: After a successful submission, the form state resets appropriately.
B. Verify has_size Handling
Ensure that the has_size flag is correctly set both at the product level and within each color.
Product Level:
For product_type: "color_size", it implies that the product has colors and each color can have sizes. Therefore, product.has_size can be false if sizes are exclusively under colors.
Color Level:
Each color that has sizes should have has_size: true.
Ensure that this flag is consistently sent from the frontend and correctly processed by the backend.
C. Confirm Data Integrity in Backend
After making changes in the frontend, verify that the backend now correctly receives and processes the data.
Logging Received Data:
Add logging in the createProduct function to inspect the incoming productData:
Ensure that color.has_size is a boolean value (true or false) and matches the intended logic.
D. Test Thoroughly After Fixes
Submit a Test Product:
Use the updated frontend to submit a product with product_type: "color_size" and colors that have sizes.
Verify Backend Response:
Ensure that the backend correctly reflects has_size: true for colors and that sizes are nested within colors.
Check Database Entries:
Inspect the database to confirm that sizes are correctly associated with their respective colors and that all flags are set as intended.
3. Additional Recommendations
A. Improve State Management
Consider using more robust state management (like Redux or Zustand) to handle complex state interactions, especially when dealing with nested structures like products with colors and sizes.
B. Validate Data on Both Ends
Implement validation on both frontend and backend to ensure data integrity. For example:
Frontend Validation: Prevent users from submitting malformed data.
Backend Validation: Ensure that incoming data adheres to the expected schema before processing.
C. Utilize TypeScript Effectively
Leverage TypeScript's strengths by defining comprehensive interfaces/types for your data structures. This can help catch discrepancies early during development.
Example Interfaces:
// Frontend Types
interface Size {
name: string;
price: string; // or number, depending on your form handling
qty: string; // or number
images: string[];
inheritImages?: boolean;
}
interface Color {
name: string;
images: string[];
hasSize: boolean;
sizes: Size[];
price: string; // or number
qty: string; // or number
inheritImages?: boolean;
}
interface Product {
name: string;
description: string;
category: string;
subcategory: string;
brand: string;
hasColor: boolean;
colors: Color[];
hasSize: boolean;
sizes: Size[];
categories: number[];
price: string; // or number
qty: string; // or number
images: string[];
}
Backend Types (CreateProductInput):
Ensure that the backend's CreateProductInput type accurately reflects the expected structure.
Ensure that your backend functions handle data consistently and that any transformations maintain the integrity of the data. Modularize code where possible to enhance readability and maintainability.
Conclusion
By addressing the duplicate form submission in your frontend and ensuring that the has_size flags are correctly set and processed, you should resolve the inconsistency between the submitted data and what's stored in your backend. Additionally, implementing robust validation and leveraging TypeScript's type-checking can prevent similar issues in the future.
If after making these adjustments the problem persists, consider the following troubleshooting steps:
Network Inspection: Use browser developer tools to inspect the actual payloads being sent in the POST requests. Ensure that has_size flags are correctly set.
Backend Logs: Enhance your backend logging to capture incoming requests comprehensively.
Database Constraints: Verify that your database schema correctly enforces relationships and constraints, preventing invalid data from being inserted.
Feel free to provide more details or ask further questions if the issue remains unresolved!