import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; import { insert, select } from '@evershop/postgres-query-builder'; import { info, success, error, warning } from '../../lib/log/logger.js'; import { pool } from '../../lib/postgres/connection.js'; import createProduct from '../../modules/catalog/services/product/createProduct.js'; import { seedProductImages } from './seedImages.js'; import { seedSamplePackage } from './seedPackages.js'; import { reportSeedSource, resolveSeedData } from './themeSeedData.js'; import { createVariantGroups, loadSeedAttributes, resolveAttributeOptions } from './variantGroupHelpers.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); /** * Seed products from JSON file */ export async function seedProducts( demoAttributeGroupId: number ): Promise { info('Seeding products...'); const { data: productsData, source } = resolveSeedData( 'products', path.join(__dirname, 'data') ); reportSeedSource('products', source); // Which attributes exist, and which of them the data allows as variant axes. // This used to look up the codes `color` and `size` by hand and abort if // either was missing, which forced every industry to keep two fashion // attributes around whether or not it used them. const { data: attributesData } = resolveSeedData( 'attributes', path.join(__dirname, 'data') ); const attributes = await loadSeedAttributes(attributesData); const referenced = new Set(); for (const p of productsData) { for (const a of p.attributes || []) { referenced.add(a.attribute_code); } } const missing = [...referenced].filter((code) => !attributes.has(code)); if (missing.length > 0) { error( `Attributes ${missing.join( ', ' )} are referenced by the products but do not exist. Run: npm run seed -- --attributes` ); return; } // Shippable products require a package_id (createProduct throws otherwise). // Ensure the demo sample package exists and reuse its id for every product // that doesn't bring its own. const samplePackage = await seedSamplePackage(); // Create variant groups const variantGroupIds = await createVariantGroups( productsData, demoAttributeGroupId, attributes ); // Seed products info('\nSeeding products...'); for (const productData of productsData) { try { // Check if product already exists const existingProduct = await select() .from('product') .where('sku', '=', productData.sku) .load(pool); if (existingProduct) { info( `Product "${productData.name}" (${productData.sku}) already exists, skipping...` ); continue; } // Assign product to the demo attribute group if (!productData.group_id) { if (!demoAttributeGroupId) { error('Demo attribute group ID is not set. This should not happen.'); continue; } productData.group_id = demoAttributeGroupId; } // Resolve category_id from the category field if (productData.category) { const categoryUrlKey = productData.category; const categoryQuery = select('category.category_id').from( 'category_description' ); categoryQuery .leftJoin('category') .on( 'category.category_id', '=', 'category_description.category_description_category_id' ); categoryQuery.where( 'category_description.url_key', '=', categoryUrlKey ); const category = await categoryQuery.load(pool); if (category && category.category_id) { productData.category_id = category.category_id; } else { warning( ` ⚠️ Category "${categoryUrlKey}" not found, product will have no category` ); } // Remove category field as it's not needed for product creation delete productData.category; } // Save collections, images, and variant_group for later processing const collections = productData.collections; const images = productData.images; const variantGroup = productData.variant_group; delete productData.collections; delete productData.images; delete productData.variant_group; // Set variant_group_id if this product belongs to a variant group if (variantGroup && variantGroupIds.has(variantGroup)) { productData.variant_group_id = variantGroupIds.get(variantGroup); info( ` → Assigning to variant group: ${variantGroup} (ID: ${productData.variant_group_id})` ); } // Convert attribute values to option IDs for select type attributes if (productData.attributes && Array.isArray(productData.attributes)) { productData.attributes = await resolveAttributeOptions( productData.attributes ); } // Shippable products need a package; assign the demo sample package when // the data doesn't specify one. Virtual products (no_shipping_required) // are exempt and left untouched. if (!productData.no_shipping_required && !productData.package_id) { productData.package_id = samplePackage.package_id; } const product = await createProduct(productData, {}); success(`✓ Created product: ${productData.name} (${productData.sku})`); // Process images if (images && Array.isArray(images)) { await seedProductImages(product.insertId, images); } // Assign product to collections if specified if (collections && Array.isArray(collections)) { for (const collectionCode of collections) { const collection = await select() .from('collection') .where('code', '=', collectionCode) .load(pool); if (collection) { await insert('product_collection') .given({ collection_id: collection.collection_id, product_id: product.insertId }) .execute(pool); info(` → Assigned to collection: ${collectionCode}`); } } } } catch (e: any) { error(`Failed to create product ${productData.name}: ${e.message}`); } } }