Files
PriceUpdaterAppv2/README.md

26 KiB

Shopify Price Updater

A comprehensive Node.js command-line tool for bulk updating Shopify product prices based on product tags using Shopify's GraphQL Admin API. Supports both price updates and rollback operations with advanced scheduling, error handling, and progress tracking.

🚀 Key Features

Core Functionality

  • 🏷️ Tag-based filtering: Update prices only for products with specific tags
  • 📊 Dual operation modes: Price updates with percentage adjustments OR rollback to original prices
  • Scheduled execution: Schedule price changes for specific dates and times
  • 🔄 Rollback capability: Revert promotional pricing using compare-at prices
  • 📈 Percentage-based adjustments: Increase or decrease prices by configurable percentages

Advanced Features

  • 🔁 Batch processing: Handles large inventories with automatic pagination
  • 🛡️ Error resilience: Continues processing even if individual products fail
  • Rate limit handling: Automatic retry logic with exponential backoff
  • 📝 Progress tracking: Detailed logging to console and Progress.md file
  • 🔍 Debug tools: Tag analysis and troubleshooting utilities
  • 🔐 Secure configuration: Environment-based credential management

Enterprise Features

  • 📊 Comprehensive reporting: Success rates, error analysis, and recommendations
  • 🎯 Validation: Pre-flight checks for products, prices, and configuration
  • ⏱️ Performance optimization: Efficient API usage and batch processing
  • 🔧 Troubleshooting: Built-in debugging and error categorization

Prerequisites

  • Node.js (version 14 or higher)
  • A Shopify store with Admin API access
  • Shopify Private App or Custom App with the following permissions:
    • read_products
    • write_products

Installation

  1. Clone or download this repository
  2. Install dependencies:
    npm install
    
  3. Copy the environment template:
    copy .env.example .env
    
  4. Configure your environment variables (see Configuration section)

🔧 Complete Functionality Overview

Operation Modes

Mode Description Use Case Configuration
Update Adjust prices by percentage Sales, promotions, price increases OPERATION_MODE=update + PRICE_ADJUSTMENT_PERCENTAGE
Rollback Revert to compare-at prices End promotions, restore original pricing OPERATION_MODE=rollback

Execution Types

Type Description When to Use
Immediate Run now Manual price updates, testing
Scheduled Run at specific time Automated sales, timed promotions

Supported Operations

Operation Capability Examples
Price Increases Positive percentages +10%, +25%, +5.5%
Price Decreases Negative percentages -15%, -30%, -12.5%
Rollback Restore original prices End sale, revert promotion
Batch Processing Handle large inventories 1000+ products
Tag Filtering Target specific products sale, clearance, seasonal

Advanced Features

Feature Description Benefit
Rate Limit Handling Automatic retry with exponential backoff Prevents API errors
Error Recovery Continue processing despite failures Maximizes success rate
Progress Tracking Real-time console + file logging Monitor operations
Validation Pre-flight checks Prevent configuration errors
Debug Tools Tag analysis and troubleshooting Identify issues quickly

Configuration

Edit the .env file with your Shopify store details:

# Your Shopify store domain (without https://)
SHOPIFY_SHOP_DOMAIN=your-store.myshopify.com

# Your Shopify Admin API access token
SHOPIFY_ACCESS_TOKEN=shpat_your_access_token_here

# The product tag to filter by
TARGET_TAG=sale

# Price adjustment percentage (positive for increase, negative for decrease)
# Examples: 10 (increase by 10%), -15 (decrease by 15%), 5.5 (increase by 5.5%)
# Note: Only used in "update" mode, ignored in "rollback" mode
PRICE_ADJUSTMENT_PERCENTAGE=10

# Operation mode - determines whether to update prices or rollback to compare-at prices
# Options: "update" (default) or "rollback"
# When not specified, defaults to "update" for backward compatibility
OPERATION_MODE=update

Operation Mode Configuration

The OPERATION_MODE environment variable controls the application behavior:

  • update (default): Performs price adjustments using PRICE_ADJUSTMENT_PERCENTAGE
  • rollback: Sets prices to compare-at price values and removes compare-at prices

When OPERATION_MODE is not specified, the application defaults to update mode for backward compatibility.

Getting Your Shopify Credentials

  1. Go to your Shopify Admin → Apps → App and sales channel settings
  2. Click "Develop apps" → "Create an app"
  3. Configure Admin API access with read_products and write_products permissions
  4. Install the app and copy the Admin API access token

For Custom Apps:

  1. Go to your Shopify Admin → Settings → Apps and sales channels
  2. Click "Develop apps" → "Create an app"
  3. Configure the required API permissions
  4. Generate and copy the access token

Usage

Basic Usage

Run the script with your configured environment:

npm start

or

node src/index.js

Operation Modes

The application supports two operation modes:

Update Mode (Default)

Adjusts product prices by a percentage:

npm run update

This performs the standard price adjustment functionality using the PRICE_ADJUSTMENT_PERCENTAGE setting.

Rollback Mode

Reverts prices by setting the main price to the compare-at price and removing the compare-at price:

npm run rollback

This is useful for reverting promotional pricing back to original prices. Products without compare-at prices will be skipped.

Operation Mode Indicators:

  • The console output clearly displays which operation mode is active
  • Progress.md logs distinguish between "Price Update Operation" and "Price Rollback Operation"
  • Configuration summary shows the operation mode being used

Debug Mode

Before running the main script, you can use the debug mode to see what tags exist in your store and verify your target tag:

npm run debug-tags

This will:

  • Show all products and their tags in your store
  • Check if your target tag exists
  • Suggest similar tags if exact match isn't found
  • Help troubleshoot tag-related issues

💡 Complete Usage Examples

Basic Price Updates

# 10% price increase for sale items
set TARGET_TAG=sale && set PRICE_ADJUSTMENT_PERCENTAGE=10 && npm run update

# 15% discount for clearance items
set TARGET_TAG=clearance && set PRICE_ADJUSTMENT_PERCENTAGE=-15 && npm run update

# 5.5% increase for seasonal products
set TARGET_TAG=seasonal && set PRICE_ADJUSTMENT_PERCENTAGE=5.5 && npm run update

Promotional Campaigns

# Black Friday: 30% off everything with "black-friday" tag
set TARGET_TAG=black-friday && set PRICE_ADJUSTMENT_PERCENTAGE=-30 && npm run update

# End of season: 50% off winter items
set TARGET_TAG=winter && set PRICE_ADJUSTMENT_PERCENTAGE=-50 && npm run update

# Flash sale: 20% off for 4 hours
set TARGET_TAG=flash-sale && set PRICE_ADJUSTMENT_PERCENTAGE=-20 && npm run update
# (Schedule rollback 4 hours later)

Rollback Operations

# End Black Friday sale (restore original prices)
set TARGET_TAG=black-friday && npm run rollback

# End clearance promotion
set TARGET_TAG=clearance && npm run rollback

# Restore all promotional pricing
set TARGET_TAG=promotion && npm run rollback

Scheduled Campaigns

# Christmas sale starts December 25th at 10:30 AM
set SCHEDULED_EXECUTION_TIME=2024-12-25T10:30:00 && set TARGET_TAG=christmas && set PRICE_ADJUSTMENT_PERCENTAGE=-25 && npm run update

# New Year sale ends January 1st at midnight
set SCHEDULED_EXECUTION_TIME=2025-01-01T00:00:00 && set TARGET_TAG=new-year && npm run rollback

# Weekend flash sale (Friday 6 PM to Sunday 11 PM)
set SCHEDULED_EXECUTION_TIME=2024-12-20T18:00:00 && set TARGET_TAG=weekend && set PRICE_ADJUSTMENT_PERCENTAGE=-35 && npm run update
set SCHEDULED_EXECUTION_TIME=2024-12-22T23:00:00 && set TARGET_TAG=weekend && npm run rollback

Advanced Scenarios

# Gradual price increase (multiple steps)
# Step 1: 5% increase
set TARGET_TAG=premium && set PRICE_ADJUSTMENT_PERCENTAGE=5 && npm run update
# Step 2: Additional 3% (total ~8.15%)
set TARGET_TAG=premium && set PRICE_ADJUSTMENT_PERCENTAGE=3 && npm run update

# A/B testing setup
set TARGET_TAG=test-group-a && set PRICE_ADJUSTMENT_PERCENTAGE=-10 && npm run update
set TARGET_TAG=test-group-b && set PRICE_ADJUSTMENT_PERCENTAGE=-15 && npm run update

# Inventory clearance (progressive discounts)
set TARGET_TAG=clearance-week1 && set PRICE_ADJUSTMENT_PERCENTAGE=-20 && npm run update
set TARGET_TAG=clearance-week2 && set PRICE_ADJUSTMENT_PERCENTAGE=-35 && npm run update
set TARGET_TAG=clearance-final && set PRICE_ADJUSTMENT_PERCENTAGE=-50 && npm run update

Configuration Examples

.env for Holiday Sale

SHOPIFY_SHOP_DOMAIN=mystore.myshopify.com
SHOPIFY_ACCESS_TOKEN=shpat_abc123...
TARGET_TAG=holiday-sale
PRICE_ADJUSTMENT_PERCENTAGE=-20
OPERATION_MODE=update
SCHEDULED_EXECUTION_TIME=2024-12-24T00:00:00

.env for Sale Rollback

SHOPIFY_SHOP_DOMAIN=mystore.myshopify.com
SHOPIFY_ACCESS_TOKEN=shpat_abc123...
TARGET_TAG=holiday-sale
OPERATION_MODE=rollback
SCHEDULED_EXECUTION_TIME=2025-01-02T00:00:00

.env for Immediate Update

SHOPIFY_SHOP_DOMAIN=mystore.myshopify.com
SHOPIFY_ACCESS_TOKEN=shpat_abc123...
TARGET_TAG=summer-collection
PRICE_ADJUSTMENT_PERCENTAGE=8
OPERATION_MODE=update
# No SCHEDULED_EXECUTION_TIME = immediate execution

📊 Monitoring & Reporting

Real-time Console Output

The application provides comprehensive real-time feedback:

🚀 Starting Shopify Price Updater
📋 Configuration:
   Store: your-store.myshopify.com
   Tag: sale
   Adjustment: +10%
   Mode: UPDATE

🔍 Found 25 products with tag 'sale'
✅ Updated Product A: $19.99 → $21.99 (Compare-at: $19.99)
✅ Updated Product B: $29.99 → $32.99 (Compare-at: $29.99)
⚠️  Skipped Product C: Invalid price data
🔄 Processing batch 2 of 3...
📊 Summary: 23 products updated, 2 skipped, 0 errors
🎉 Operation completed successfully!

Progress.md Logging

Persistent logging with detailed information:

# Shopify Price Update Progress Log

## Operation: Price Update - 2024-08-19 15:30:45

- **Store**: your-store.myshopify.com
- **Tag**: sale
- **Mode**: UPDATE (+10%)
- **Products Found**: 25
- **Variants Processed**: 47

### Results Summary

-**Successful Updates**: 45 (95.7%)
-**Failed Updates**: 2 (4.3%)
- ⏱️ **Duration**: 12 seconds

### Error Analysis

- Validation errors: 1
- Network errors: 1
- Recommendations: Check product data for SKU-12345

Success Rate Indicators

Success Rate Status Action
90-100% 🎉 Excellent Operation successful
70-89% ⚠️ Good Review minor issues
50-69% ⚠️ Moderate Investigate errors
<50% Poor Check configuration

Monitoring Features

  • 📈 Real-time progress: Live updates during processing
  • 📊 Success metrics: Detailed success/failure rates
  • 🔍 Error categorization: Grouped by error type
  • ⏱️ Performance tracking: Operation duration and speed
  • 📝 Historical logs: Complete operation history
  • 🎯 Recommendations: Actionable suggestions for issues

Error Handling

The script is designed to be resilient:

  • Rate Limits: Automatically retries with exponential backoff
  • Network Issues: Retries failed requests up to 3 times
  • Invalid Data: Skips problematic products and continues
  • API Errors: Logs errors and continues with remaining products
  • Missing Environment Variables: Validates configuration before starting

Testing

Before Running on Production

  1. Test with a development store or backup your data
  2. Start with a small subset by using a specific tag with few products
  3. Verify the percentage calculation with known product prices
  4. Check the Progress.md file to ensure logging works correctly
  1. Create a test tag (e.g., "price-test") on a few products
  2. Set TARGET_TAG=price-test in your .env
  3. Run the script with a small percentage (e.g., 1%)
  4. Verify the changes in your Shopify admin
  5. Once satisfied, update your configuration for the actual run

🔧 Troubleshooting & FAQ

Common Issues & Solutions

Issue Symptoms Solution
Authentication Failed 401 Unauthorized errors • Verify SHOPIFY_ACCESS_TOKEN
• Check app permissions (read_products, write_products)
No Products Found 0 products found message • Run npm run debug-tags
• Check tag spelling (case-sensitive)
• Verify products have the tag
Rate Limit Exceeded 429 Rate limit errors • Script handles automatically
• Reduce batch size if persistent
Invalid Percentage Configuration errors • Use numbers only: 10, -15, 5.5
• Negative for decreases
Scheduling Errors Invalid time format • Use ISO 8601: 2024-12-25T10:30:00
• Ensure future date

Debugging Workflow

# Step 1: Check configuration
npm run debug-tags

# Step 2: Test with small subset
# Set TARGET_TAG to a tag with few products
# Set PRICE_ADJUSTMENT_PERCENTAGE to 1

# Step 3: Run test update
npm run update

# Step 4: Verify in Shopify admin
# Check that prices changed correctly

# Step 5: Test rollback
npm run rollback

# Step 6: Check Progress.md for detailed logs

Debug Tools & Commands

Tool Command Purpose
Tag Analysis npm run debug-tags • List all store tags
• Find similar tags
• Verify tag existence
Progress Logs Check Progress.md • Detailed operation history
• Error messages
• Success/failure rates
Test Mode Small percentage test • Verify configuration
• Test API connectivity
• Validate results

Frequently Asked Questions

Q: Can I undo price changes? A: Yes! Use rollback mode (npm run rollback) to revert to compare-at prices.

Q: How do I schedule multiple operations? A: Run separate commands with different SCHEDULED_EXECUTION_TIME values.

Q: What happens if the script fails mid-operation? A: The script continues processing remaining products and logs all errors. Partial updates are preserved.

Q: Can I target multiple tags? A: Currently supports one tag per operation. Run multiple operations for different tags.

Q: How do I handle large inventories? A: The script automatically handles pagination and rate limiting for any inventory size.

Q: What's the maximum percentage change? A: No hard limit, but be cautious with large changes. Test with small percentages first.

Error Categories & Meanings

Category Description Action Required
Authentication Invalid credentials Update .env file
Validation Invalid data format Check product data
Rate Limiting API limits exceeded Automatic retry (no action)
Network Connection issues Check internet, retry
Configuration Invalid settings Review .env configuration

Security Notes

  • Never commit your .env file to version control
  • Use environment-specific access tokens
  • Regularly rotate your API credentials
  • Test changes in a development environment first

File Structure

shopify-price-updater/
├── src/
│   ├── config/
│   │   └── environment.js     # Environment configuration
│   ├── services/
│   │   ├── shopify.js         # Shopify API client
│   │   ├── product.js         # Product operations
│   │   └── progress.js        # Progress logging
│   ├── utils/
│   │   ├── price.js           # Price calculations
│   │   └── logger.js          # Logging utilities
│   └── index.js               # Main entry point
├── tests/                    # Unit tests for the application
├── debug-tags.js            # Debug script to analyze store tags
├── .env                     # Your configuration (create from .env.example)
├── .env.example            # Configuration template
├── package.json            # Dependencies and scripts
├── Progress.md             # Generated progress log
└── README.md               # This file

🔧 Technical Specifications

API Integration

Component Specification Details
API Version Shopify GraphQL Admin API 2024-01 Latest stable version
Authentication Private App Access Tokens Secure token-based auth
HTTP Client Node.js native HTTPS No external dependencies
Mutations productVariantsBulkUpdate Efficient batch updates
Queries products with pagination Cursor-based pagination

Performance & Scalability

Metric Specification Notes
Batch Size 10 variants per batch Optimized for rate limits
Page Size 50 products per page Shopify recommended
Retry Logic 3 attempts with exponential backoff 1s, 2s, 4s delays
Rate Limiting Automatic handling Respects Shopify limits
Memory Usage Streaming processing Handles large inventories

Error Handling & Recovery

Error Type Handling Strategy Recovery Action
Rate Limits (429) Exponential backoff retry Automatic retry with delays
Network Errors Connection retry Up to 3 attempts
Validation Errors Skip and continue Log error, process next
Authentication (401) Immediate failure Check credentials
Server Errors (5xx) Retry with backoff Automatic recovery

Data Processing

Feature Implementation Benefit
Price Calculations Decimal precision handling Accurate currency math
Tag Formatting Automatic "tag:" prefix Shopify compatibility
Validation Pre-flight checks Prevent invalid operations
Rollback Logic Compare-at price restoration Safe promotional reversals
Progress Tracking Real-time status updates Operation visibility

Security Features

Security Aspect Implementation Protection
Credential Storage Environment variables No hardcoded secrets
API Token Validation Format and length checks Invalid token detection
Input Sanitization Parameter validation Injection prevention
Error Logging Sanitized error messages No credential exposure
Rate Limit Respect Built-in throttling API abuse prevention

System Requirements

Requirement Minimum Recommended
Node.js v16.0.0+ v18.0.0+
Memory 512MB 1GB+
Network Stable internet High-speed connection
Storage 100MB 500MB+ (for logs)
Shopify Plan Basic Shopify Plus (for high volume)

Supported Operations

Operation Capability Limitations
Price Updates Any percentage change Must result in positive prices
Rollback Restore from compare-at prices Requires existing compare-at prices
Scheduling ISO 8601 datetime Future dates only
Tag Filtering Single tag per operation Case-sensitive matching
Batch Processing Unlimited products Rate limit dependent

📋 Available Scripts & Commands

Core Operations

Command Description Use Case
npm start Run with default settings General price updates
npm run update Explicit update mode Price adjustments with percentage
npm run rollback Rollback mode Revert to original prices
npm run debug-tags Tag analysis tool Troubleshooting and discovery
npm test Run test suite Development and validation

Advanced Usage Examples

# Basic price update
npm start

# Explicit update mode with 10% increase
set OPERATION_MODE=update && set PRICE_ADJUSTMENT_PERCENTAGE=10 && npm start

# Rollback promotional pricing
set OPERATION_MODE=rollback && npm start

# Debug tag issues
npm run debug-tags

# Scheduled execution (Christmas sale start)
set SCHEDULED_EXECUTION_TIME=2024-12-25T10:30:00 && npm run update

# Scheduled rollback (New Year sale end)
set SCHEDULED_EXECUTION_TIME=2025-01-01T00:00:00 && npm run rollback

Scheduled Execution

Schedule price changes for specific dates and times using the SCHEDULED_EXECUTION_TIME environment variable.

Scheduling Formats

Format Example Description
Local time 2024-12-25T10:30:00 Uses system timezone
UTC time 2024-12-25T10:30:00Z Universal Coordinated Time
Timezone specific 2024-12-25T10:30:00-05:00 Eastern Standard Time

Common Scheduling Scenarios

# Black Friday sale start (25% off)
set SCHEDULED_EXECUTION_TIME=2024-11-29T00:00:00 && set PRICE_ADJUSTMENT_PERCENTAGE=-25 && npm run update

# Christmas sale start (15% off)
set SCHEDULED_EXECUTION_TIME=2024-12-25T10:30:00 && set PRICE_ADJUSTMENT_PERCENTAGE=-15 && npm run update

# New Year sale end (rollback to original prices)
set SCHEDULED_EXECUTION_TIME=2025-01-01T00:00:00 && npm run rollback

# Flash sale (2-hour window)
set SCHEDULED_EXECUTION_TIME=2024-12-15T14:00:00 && set PRICE_ADJUSTMENT_PERCENTAGE=-30 && npm run update
# Then schedule rollback 2 hours later
set SCHEDULED_EXECUTION_TIME=2024-12-15T16:00:00 && npm run rollback

Using .env File for Scheduling

# Complete scheduled configuration
SCHEDULED_EXECUTION_TIME=2024-12-25T10:30:00
OPERATION_MODE=update
TARGET_TAG=holiday-sale
PRICE_ADJUSTMENT_PERCENTAGE=-20
SHOPIFY_SHOP_DOMAIN=your-store.myshopify.com
SHOPIFY_ACCESS_TOKEN=your_token_here

Scheduling Features

  • 📅 Countdown display: Shows time remaining until execution
  • Cancellation support: Press Ctrl+C to cancel during countdown
  • 🔒 Safe execution: Cannot cancel during active price updates
  • 📝 Logging: All scheduled operations are logged with timestamps
  • ⚠️ Validation: Validates scheduled time format and future date

License

This project is provided as-is for educational and commercial use. Please test thoroughly before using in production environments.