const tariffTemplates = require('../tariffData.json') module.exports = async function(pg, items) { await checkForPreviousItems(pg); const {itemCounts, itemImages} = await createItems(pg, items); await createShipment(pg, itemCounts); return itemImages.map(({uuid, name, images}) => ({ uuid, name, images: images.map(image => image.replace(/^thumb\//, '')) })) } async function checkForPreviousItems(pg) { const items = await pg.item.findAll(); if(items.length) throw new Error(`Cannot migrate items - ${items.length} items already exist!`) } async function createItems(pg, items) { const itemCounts = []; const itemImages = []; for (const item of items) { let tariffData = null; if(item.tags.includes('fauxpaws')) tariffData = tariffTemplates.sock; if(item.tags.includes('tinyequine')) tariffData = tariffTemplates.sock; if(!tariffData) { console.warn(` Skipping item ${item.name} because of missing tariff data`) continue; } const newItem = await pg.item.create( item.name, item.urlslug, item.description .replace(/<(\/|)p>/g, '') .replace(' ', ' ') .trim(), item.price * 100, true, tariffData.hs_tariff_number, tariffData.customs_description, tariffData.origin_country, tariffData.weight ) itemCounts.push({ uuid: newItem.uuid, count: item.numberInStock }) itemImages.push({ uuid: newItem.uuid, name: newItem.name, images: [ item.productImage, ...item.images ] }) } return {itemCounts, itemImages}; } async function createShipment(pg, itemCounts) { return await pg.shipment.createShipment( "Initial stock from db import", itemCounts.filter(({count}) => count > 0) ); }