Untitled

 avatar
unknown
plain_text
a year ago
4.1 kB
12
Indexable
const dotenv = require('dotenv');
const Shopify = require('shopify-api-node');
const Bottleneck = require('bottleneck');

dotenv.config();

const INVENTORY_BUFFER = 2;

const sourceShopify = new Shopify({
  shopName: process.env.SOURCE_SHOP_NAME,
  accessToken: process.env.SOURCE_SHOPIFY_ACCESS_TOKEN,
  accessMode: 'private',
  apiVersion: '2021-07',
  scopes: ['read_inventory', 'read_products']
});

const destinationShopify = new Shopify({
  shopName: process.env.DESTINATION_SHOP_NAME,
  accessToken: process.env.DESTINATION_SHOPIFY_ACCESS_TOKEN,
  accessMode: 'private',
  apiVersion: '2024-04',
  scopes: ['read_inventory', 'write_inventory', 'read_products']
});

sourceShopify.shop.get()
  .then(shop => {
    console.log('Connected to Source Shopify successfully.');
  })
  .catch(err => {
    console.error('Failed to connect to Source Shopify:', err);
  });

destinationShopify.shop.get()
  .then(shop => {
    console.log('Connected to Destination Shopify successfully.');
  })
  .catch(err => {
    console.error('Failed to connect to Destination Shopify:', err);
  });

// LIST IS ONLY FETCHING FIRST 50 PRODUCTS, ADD RATE LIMIT FOR SHOPIFY API

// Function to fetch all source products inventory
async function getAllProducts() {
  try {
    const products = await sourceShopify.product.list();
    console.log(`${products.length} products found in the source store.`);
    return products.map(product => ({
      id: product.id,
      title: product.title,
      SKU: product.variants[0].sku,
      barcode: product.variants[0].barcode,
      inventory: product.variants[0].inventory_quantity - INVENTORY_BUFFER
    }));
  } catch (error) {
    console.error('Failed to fetch products:', error);
    return [];
  }
}

// UPDATE INVENTORY NOT WORKING

// Function to update inventory in destination store
async function updateDestinationStore(products) {
    try {
      // Fetch product list from the destination store
      const destinationProducts = await destinationShopify.product.list();
  
      for (const product of products) {
        // Find corresponding product in destination store by barcode
        const destinationProduct = destinationProducts.find(p =>
          p.variants.some(v => v.barcode === product.barcode)
        );
  
        if (destinationProduct) {
          const variantToUpdate = destinationProduct.variants.find(v => v.barcode === product.barcode);
          await destinationShopify.productVariant.update(variantToUpdate.id, {
            inventory_quantity: product.inventory
          });
          console.log(`Inventory updated for product ${product.title} with barcode ${product.barcode}`);
        } else {
          // Check if product exists in source store
          const sourceProducts = await sourceShopify.product.list();
          const sourceProduct = sourceProducts.find(p =>
            p.variants.some(v => v.barcode === product.barcode)
          );
          if (!sourceProduct) {
            console.error(`No matching product found in source store for barcode ${product.barcode}`);
          } else {
            console.error(`No matching product found in destination store for barcode ${product.barcode}`);
          }
        }
      }
    } catch (error) {
    if (error.response && error.response.statusCode === 403) {
        console.error('Failed to update inventory in the destination store: You do not have permission to perform this action.');
        } else {
        console.error(`Failed to update inventory for product with barcode ${product.barcode} in the destination store:`, error);
        }
      }
    }
  
// Rate limiting configuration
const limiter = new Bottleneck({
  maxConcurrent: 1, // Number of concurrent requests
  minTime: 2000 // Minimum time between each request (in milliseconds)
});

// Fetch products and update inventory with rate limiting
limiter.schedule(getAllProducts)
  .then(products => {
    console.table(products);
    return updateDestinationStore(products);
  })
  .catch(error => {
    console.error('Error during product fetch or inventory update:', error);
  });
Editor is loading...
Leave a Comment