Top 100 Developer Tooling and Productivity SaaS Ideas to Launch in 2026 for Modern E-commerce Founders and Store Owners
Automated A/B Testing for Product Descriptions with NLP Analysis
E-commerce store owners often struggle to optimize product descriptions for maximum conversion. Manually testing variations is time-consuming and requires deep copywriting expertise. A SaaS offering that automates this process using Natural Language Processing (NLP) for sentiment analysis and keyword density evaluation would be invaluable. This tool could dynamically generate and test multiple description variants, learning which phrasing, tone, and keyword combinations resonate best with specific customer segments.
The core of such a system would involve a robust NLP pipeline. For generating variants, we can leverage pre-trained language models like GPT-3 or fine-tune smaller, more specialized models on e-commerce product data. For analysis, libraries like spaCy or NLTK in Python are essential.
Technical Implementation Sketch (Python)
Consider a Python-based backend using Flask or FastAPI for the API. The NLP processing could be handled by a dedicated microservice.
Variant Generation Endpoint
from flask import Flask, request, jsonify
# Assume 'generate_variants' is a function that uses an NLP model
# to create diverse product description variations.
from nlp_service import generate_variants
app = Flask(__name__)
@app.route('/generate-description-variants', methods=['POST'])
def handle_generate_variants():
data = request.get_json()
product_details = data.get('product_details')
num_variants = data.get('num_variants', 5)
if not product_details:
return jsonify({"error": "Missing product_details"}), 400
try:
variants = generate_variants(product_details, num_variants)
return jsonify({"variants": variants})
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
app.run(debug=True, port=5001)
A/B Testing Orchestration and Analysis
The A/B testing logic would involve integrating with e-commerce platform APIs (e.g., Shopify, WooCommerce) to dynamically update product descriptions and track conversion metrics. A separate service would analyze the results, potentially using statistical significance tests (e.g., t-tests, chi-squared tests) to determine winning variants. Sentiment analysis on customer reviews related to products with different descriptions could also be a powerful feedback loop.
import requests
import pandas as pd
from scipy import stats
# Assume 'analyze_sentiment' is a function using a sentiment analysis model
from nlp_service import analyze_sentiment
def run_ab_test(product_id, variants_data):
# 1. Deploy variants to e-commerce platform (via API)
# This involves updating product descriptions for product_id
# and assigning traffic to each variant.
# 2. Collect conversion data over a period
# (e.g., views, add-to-carts, purchases for each variant)
conversion_data = collect_conversion_data(product_id) # Placeholder
# 3. Analyze results
results = []
for variant_name, metrics in conversion_data.items():
# Calculate conversion rate, etc.
conversion_rate = metrics['purchases'] / metrics['views'] if metrics['views'] > 0 else 0
results.append({'variant': variant_name, 'conversion_rate': conversion_rate, 'metrics': metrics})
df_results = pd.DataFrame(results)
# Statistical significance testing (e.g., comparing variant A vs. B)
# This is a simplified example; more robust statistical methods are needed.
if len(df_results) > 1:
# Example: Compare the first variant against all others
base_variant = df_results.iloc[0]
for i in range(1, len(df_results)):
other_variant = df_results.iloc[i]
# Perform t-test on conversion rates (requires more sophisticated data handling)
# For simplicity, let's just compare rates and flag significant differences
if other_variant['conversion_rate'] > base_variant['conversion_rate'] * 1.1: # > 10% improvement
print(f"Variant {other_variant['variant']} shows potential improvement over {base_variant['variant']}")
# Further analysis: sentiment analysis on reviews for this product
related_reviews = get_product_reviews(product_id) # Placeholder
sentiment_scores = [analyze_sentiment(review) for review in related_reviews]
avg_sentiment = sum(sentiment_scores) / len(sentiment_scores) if sentiment_scores else 0
print(f"Average sentiment for {product_id}: {avg_sentiment}")
# 4. Recommend winning variant or further testing
winning_variant = df_results.loc[df_results['conversion_rate'].idxmax()]
return winning_variant
def collect_conversion_data(product_id):
# Placeholder: In a real system, this would query your analytics DB
# or platform API for data segmented by variant.
return {
"variant_A": {"views": 1000, "purchases": 50},
"variant_B": {"views": 950, "purchases": 65},
"variant_C": {"views": 1050, "purchases": 55}
}
def get_product_reviews(product_id):
# Placeholder: Fetch reviews from your database or review service.
return ["This product is amazing!", "It broke after a week.", "Great value for money."]
# Example usage:
# variants = ["Original Description", "Variant 1: Focus on durability", "Variant 2: Emphasize ease of use"]
# winning_variant_info = run_ab_test("prod_123", variants)
# print(f"Recommended winning variant: {winning_variant_info['variant']}")
AI-Powered Inventory Forecasting and Replenishment Automation
Accurate inventory management is critical for e-commerce. Stockouts lead to lost sales and customer dissatisfaction, while overstocking ties up capital and increases storage costs. A SaaS that leverages machine learning to predict demand with high accuracy and automate reordering based on lead times, seasonality, and promotional events would be a game-changer.
Core Components and Data Inputs
The system needs to ingest historical sales data, product attributes (category, price, seasonality), marketing calendar (promotions, ad spend), and supplier lead times. Time-series forecasting models like ARIMA, Prophet, or more advanced deep learning models (e.g., LSTMs) can be employed.
Demand Forecasting Model (Python Example)
from prophet import Prophet
import pandas as pd
def forecast_demand(historical_sales_df, future_dates_df):
"""
Forecasts demand using Facebook's Prophet model.
Args:
historical_sales_df (pd.DataFrame): DataFrame with columns 'ds' (datetime)
and 'y' (sales volume).
future_dates_df (pd.DataFrame): DataFrame with column 'ds' (future datetimes).
Returns:
pd.DataFrame: DataFrame with forecasted values.
"""
model = Prophet(
yearly_seasonality=True,
weekly_seasonality=True,
daily_seasonality=False, # Adjust based on data granularity
changepoint_prior_scale=0.05 # Tune this parameter
)
# Add holidays and special events if available
# holidays = pd.DataFrame({
# 'holiday': 'black_friday',
# 'ds': pd.to_datetime(['2023-11-24', '2024-11-29']),
# 'lower_window': 0,
# 'upper_window': 1,
# })
# model.add_country_holidays(country_name='US') # Example for US holidays
# model.add_new_holidays(holidays)
model.fit(historical_sales_df)
forecast = model.predict(future_dates_df)
# Filter for relevant columns and potentially add confidence intervals
return forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']]
# Example Usage:
# Assuming you have historical_sales.csv and future_dates.csv
# historical_df = pd.read_csv('historical_sales.csv')
# historical_df['ds'] = pd.to_datetime(historical_df['ds'])
# future_df = pd.read_csv('future_dates.csv')
# future_df['ds'] = pd.to_datetime(future_df['ds'])
#
# demand_forecast = forecast_demand(historical_df, future_df)
# print(demand_forecast.head())
Replenishment Logic and Integration
The replenishment module would take the demand forecast, current stock levels, and supplier lead times to calculate optimal reorder points and quantities. This would trigger automated purchase orders or alerts to procurement teams. Integration with ERP systems and supplier portals would be key.
def calculate_reorder_point(demand_forecast_mean, lead_time_days, safety_stock_factor=1.5):
"""
Calculates the reorder point.
Reorder Point = (Average Daily Demand * Lead Time in Days) + Safety Stock
"""
avg_daily_demand = demand_forecast_mean # Assuming forecast is daily
safety_stock = avg_daily_demand * safety_stock_factor # Simple safety stock calculation
reorder_point = (avg_daily_demand * lead_time_days) + safety_stock
return reorder_point
def determine_reorder_quantity(current_stock, reorder_point, demand_forecast_period, max_stock_level=None):
"""
Determines the quantity to reorder.
"""
if current_stock < reorder_point:
# Quantity to order to reach max_stock_level or cover demand for forecast period
target_level = max_stock_level if max_stock_level else reorder_point + demand_forecast_period
quantity_to_order = max(0, target_level - current_stock)
return quantity_to_order
return 0
# Example:
# Assuming demand_forecast is a DataFrame from the Prophet model
# current_stock = 150
# lead_time_days = 7
# forecast_period_days = 30 # Forecast for the next 30 days
# max_stock_level = 500
#
# # Get average demand for the relevant period from the forecast
# # For simplicity, let's use the mean of the forecast for the next lead_time_days
# avg_demand_for_lead_time = demand_forecast['yhat'].iloc[0:lead_time_days].mean()
#
# reorder_point = calculate_reorder_point(avg_demand_for_lead_time, lead_time_days)
# quantity_to_order = determine_reorder_quantity(current_stock, reorder_point, forecast_period_days, max_stock_level)
#
# print(f"Current Stock: {current_stock}")
# print(f"Reorder Point: {reorder_point:.2f}")
# print(f"Quantity to Order: {quantity_to_order:.2f}")
#
# if quantity_to_order > 0:
# print("Triggering reorder process...")
# # Initiate purchase order creation via API or internal workflow
Intelligent Shipping Rate Optimization and Carrier Selection
Shipping costs are a significant factor in e-commerce profitability and customer satisfaction. A SaaS that dynamically selects the optimal shipping carrier and service level based on real-time rates, delivery speed requirements, package dimensions, destination, and historical carrier performance would provide substantial savings and improve delivery reliability.
API Integrations and Rate Aggregation
This tool would need to integrate with multiple shipping carrier APIs (e.g., FedEx, UPS, USPS, DHL, regional carriers) and potentially multi-carrier shipping platforms (e.g., Shippo, EasyPost). The core logic would involve fetching rates for all available options for a given shipment and comparing them against defined business rules.
Rate Fetching and Comparison Logic (Conceptual Python)
import requests
import json
# Placeholder for carrier API client classes
class FedExAPI:
def get_rates(self, shipment_details):
# Simulate API call to FedEx
response = requests.post("https://api.fedex.com/rates", json=shipment_details)
# Parse response and return rates
return [{"service": "FEDEX_GROUND", "cost": 15.50, "delivery_estimate": "3-5 days"},
{"service": "FEDEX_2_DAY", "cost": 25.00, "delivery_estimate": "2 days"}]
class UPSAPI:
def get_rates(self, shipment_details):
# Simulate API call to UPS
response = requests.post("https://api.ups.com/rates", json=shipment_details)
return [{"service": "GROUND", "cost": 14.75, "delivery_estimate": "3-5 days"},
{"service": "2ND_DAY_AIR", "cost": 24.50, "delivery_estimate": "2 days"}]
# ... other carrier APIs
def optimize_shipping(shipment_details, business_rules):
"""
Fetches rates from multiple carriers and selects the optimal one.
Args:
shipment_details (dict): Contains origin, destination, package dimensions, weight.
business_rules (dict): Defines preferences (e.g., max cost, preferred carriers, max delivery time).
Returns:
dict: The selected shipping option or None.
"""
all_rates = []
carriers = [FedExAPI(), UPSAPI()] # Add more carriers
for carrier in carriers:
try:
rates = carrier.get_rates(shipment_details)
for rate in rates:
rate['carrier'] = carrier.__class__.__name__ # Add carrier name
all_rates.append(rate)
except Exception as e:
print(f"Error fetching rates from {carrier.__class__.__name__}: {e}")
if not all_rates:
return None
# Apply business rules for filtering and selection
eligible_rates = []
for rate in all_rates:
# Example rule: Max cost
if rate['cost'] > business_rules.get('max_cost', float('inf')):
continue
# Example rule: Max delivery time
if rate['delivery_estimate'].endswith('days') and int(rate['delivery_estimate'].split('-')[1].replace(' days', '')) > business_rules.get('max_delivery_days', 7):
continue
# Example rule: Preferred carriers
if business_rules.get('preferred_carriers') and rate['carrier'] not in business_rules['preferred_carriers']:
continue
eligible_rates.append(rate)
if not eligible_rates:
return None
# Select the best option (e.g., cheapest, fastest if costs are equal)
# This logic can be complex based on business priorities.
# Simple example: sort by cost, then by delivery speed (shorter first)
eligible_rates.sort(key=lambda x: (x['cost'], int(x['delivery_estimate'].split('-')[0].replace(' days', ''))))
return eligible_rates[0]
# Example Usage:
# shipment = {
# "origin": {"zip": "90210", "country": "US"},
# "destination": {"zip": "10001", "country": "US"},
# "package": {"weight": 5, "dimensions": {"length": 10, "width": 8, "height": 6, "unit": "IN"}}
# }
# rules = {"max_cost": 20.00, "max_delivery_days": 5, "preferred_carriers": ["UPSAPI"]}
#
# best_option = optimize_shipping(shipment, rules)
# if best_option:
# print(f"Recommended Shipping: {best_option['carrier']} - {best_option['service']} (${best_option['cost']:.2f})")
# else:
# print("Could not find a suitable shipping option.")
Automated Customer Review and Feedback Management
Managing customer feedback across multiple channels (product pages, marketplaces, social media) is a significant operational burden. A SaaS that aggregates reviews, identifies trends, flags negative sentiment for immediate action, and even automates responses for common queries would streamline customer service and reputation management.
Data Aggregation and Sentiment Analysis Pipeline
This involves building scrapers or using APIs to pull reviews from various sources. NLP techniques are crucial for sentiment analysis, topic modeling (to identify common themes), and keyword extraction. A dashboard would visualize this data, highlighting key insights.
Review Aggregation and Sentiment Scoring (Python Example)
from textblob import TextBlob
import requests
import json
from collections import defaultdict
# Placeholder for review fetching functions
def fetch_reviews_from_platform(platform_url):
# Simulate fetching reviews from a platform like Trustpilot or an e-commerce site
# In reality, this would involve API calls or web scraping.
print(f"Fetching reviews from {platform_url}...")
# Dummy data structure
return [
{"id": "rev1", "product_id": "prod_A", "rating": 5, "text": "Absolutely love this product! Highly recommend."},
{"id": "rev2", "product_id": "prod_B", "rating": 1, "text": "Terrible quality, broke after one use. Very disappointed."},
{"id": "rev3", "product_id": "prod_A", "rating": 4, "text": "Good value, but the instructions were a bit unclear."},
{"id": "rev4", "product_id": "prod_C", "rating": 3, "text": "It's okay, does the job but nothing special."},
]
def get_sentiment(text):
"""
Uses TextBlob for basic sentiment analysis.
Returns polarity (-1.0 to 1.0) and subjectivity (0.0 to 1.0).
"""
analysis = TextBlob(text)
return analysis.sentiment.polarity, analysis.sentiment.subjectivity
def analyze_feedback(review_sources):
"""
Aggregates reviews and performs sentiment analysis.
Args:
review_sources (list): List of URLs or identifiers for review platforms.
Returns:
dict: Aggregated data including sentiment scores and common themes.
"""
all_reviews = []
for source in review_sources:
all_reviews.extend(fetch_reviews_from_platform(source))
sentiment_summary = defaultdict(list)
product_feedback = defaultdict(lambda: {"positive": 0, "neutral": 0, "negative": 0, "total": 0, "avg_rating": 0, "reviews": []})
for review in all_reviews:
polarity, subjectivity = get_sentiment(review['text'])
review['polarity'] = polarity
review['subjectivity'] = subjectivity
sentiment_label = "neutral"
if polarity > 0.2:
sentiment_label = "positive"
elif polarity < -0.2:
sentiment_label = "negative"
sentiment_summary[sentiment_label].append(review)
# Aggregate by product
pid = review['product_id']
product_feedback[pid]["total"] += 1
product_feedback[pid]["avg_rating"] = (product_feedback[pid]["avg_rating"] * (product_feedback[pid]["total"] - 1) + review['rating']) / product_feedback[pid]["total"]
product_feedback[pid][sentiment_label] += 1
product_feedback[pid]["reviews"].append(review)
# Further analysis could include topic modeling on negative reviews
# to identify recurring issues (e.g., "shipping delay", "poor material").
return {
"sentiment_summary": {k: len(v) for k, v in sentiment_summary.items()},
"product_feedback": dict(product_feedback),
"all_processed_reviews": all_reviews
}
# Example Usage:
# sources = ["http://example.com/reviews/productA", "http://marketplace.com/productA"]
# feedback_data = analyze_feedback(sources)
# print(json.dumps(feedback_data["sentiment_summary"], indent=2))
# print(json.dumps(feedback_data["product_feedback"]["prod_A"], indent=2))
Automated Response Generation
For negative reviews or common questions, AI can generate draft responses. This could involve templated responses augmented with specific details from the review and sentiment analysis, requiring human review before sending. For positive reviews, a simple “Thank you!” with personalization can suffice.
def generate_response(review, sentiment_label):
"""
Generates a draft response based on review sentiment.
"""
product_name = review.get('product_name', 'your product') # Assume product name is available
customer_name = review.get('customer_name', 'valued customer') # Assume customer name is available
if sentiment_label == "positive":
return f"Dear {customer_name},\n\nThank you for your wonderful review of {product_name}! We're thrilled you love it. Your feedback is greatly appreciated!\n\nBest regards,\n[Your Store Name]"
elif sentiment_label == "negative":
return f"Dear {customer_name},\n\nWe are very sorry to hear about your negative experience with {product_name}. We take feedback like yours seriously and would like to investigate this further. Please contact us directly at [support_email] so we can help resolve this issue.\n\nSincerely,\n[Your Store Name]"
else: # Neutral
return f"Dear {customer_name},\n\nThank you for your feedback on {product_name}. We appreciate you taking the time to share your thoughts.\n\nRegards,\n[Your Store Name]"
# Example Usage:
# sample_review = {"id": "rev2", "product_id": "prod_B", "rating": 1, "text": "Terrible quality, broke after one use. Very disappointed.", "customer_name": "Jane Doe"}
# polarity, _ = get_sentiment(sample_review['text'])
# sentiment = "negative" if polarity < -0.2 else ("positive" if polarity > 0.2 else "neutral")
#
# draft_response = generate_response(sample_review, sentiment)
# print(draft_response)
Personalized Product Recommendation Engine with Real-time Behavior Tracking
Generic product recommendations are often ineffective. A sophisticated SaaS that tracks user behavior in real-time (page views, add-to-carts, search queries, purchase history) and uses collaborative filtering, content-based filtering, or hybrid approaches to deliver highly personalized recommendations can significantly boost conversion rates and average order value.
Recommendation Algorithms and Data Ingestion
The system needs a robust data pipeline to capture user interactions. This data feeds into recommendation algorithms. For real-time updates, in-memory data stores like Redis can be used to cache user profiles and recent activity.
Hybrid Recommendation System (Conceptual Python)
from sklearn.metrics.pairwise import cosine_similarity
import pandas as pd
import numpy as np
class RecommendationEngine:
def __init__(self, products_df, user_interactions_df):
"""
Initializes the recommendation engine.
products_df: DataFrame with product features (e.g., category, tags, description embeddings).
user_interactions_df: DataFrame with user interactions (user_id, product_id, interaction_type, timestamp).
"""
self.products_df = products_df
self.user_interactions_df = user_interactions_df
self.product_similarity_matrix = None
self.user_item_matrix = None
self.user_similarity_matrix = None
self._build_models()
def _build_models(self):
# Content-based filtering: Calculate product similarity based on features
# For simplicity, let's assume we have pre-computed embeddings or TF-IDF vectors
# product_features = self.products_df[['embedding_vector']] # Example
# self.product_similarity_matrix = cosine_similarity(product_features)
# self.products_df['product_id'] = self.products_df['product_id'].astype(str) # Ensure consistent types
# self.product_similarity_matrix = pd.DataFrame(self.product_similarity_matrix, index=self.products_df['product_id'], columns=self.products_df['product_id'])
# Collaborative filtering: Create user-item interaction matrix
self.user_item_matrix = self.user_interactions_df.pivot_table(
index='user_id', columns='product_id', aggfunc='size', fill_value=0
)
# Ensure all product IDs from products_df are columns, even if no interactions yet
for pid in self.products_df['product_id']:
if pid not in self.user_item_matrix.columns:
self.user_item_matrix[pid] = 0
# Calculate user similarity
self.user_similarity_matrix = cosine_similarity(self.user_item_matrix)
self.user_similarity_matrix = pd.DataFrame(self.user_similarity_matrix, index=self.user_item_matrix.index, columns=self.user_item_matrix.index)
def get_content_based_recommendations(self, product_id, n=5):
""" Recommends similar products based on content. """
if self.product_similarity_matrix is None:
return []
if product_id not in self.product_similarity_matrix.columns:
return []
similar_products = self.product_similarity_matrix[product_id].sort_values(ascending=False)
# Exclude the product itself and return top N
return similar_products.drop(product_id).head(n).index.tolist()
def get_collaborative_filtering_recommendations(self, user_id, n=5):
""" Recommends products based on similar users' preferences. """
if user_id not in self.user_similarity_matrix.index:
return []
# Get users similar to the target user
similar_users = self.user_similarity_matrix[user_id].sort_values(ascending=False)
similar_users = similar_users.drop(user_id) # Exclude the user itself
# Get items the target user has interacted with
user_items = set(self.user_item_matrix.loc[user_id][self.user_item_matrix.loc[user_id] > 0].index)
# Aggregate recommendations from similar users, prioritizing items not yet seen by the target user
recommendations = {}
for sim_user, similarity_score in similar_users.items():
if similarity_score < 0.1: # Threshold for similarity
continue
sim_user_items = set(self.user_item_matrix.loc[sim_user][self.user_item_matrix.loc[sim_user] > 0].index)
new_items = sim_user_items - user_items
for item in new_items:
recommendations[item] = recommendations.get(item, 0) + similarity_score # Weight by similarity
# Sort recommendations by score
sorted_recommendations = sorted(recommendations.items(), key=lambda item: item[1], reverse=True)
return [item[0] for item in sorted_recommendations[:n]]
def get_hybrid_recommendations(self, user_id, current_product_id=None, n=5):
""" Combines content-based and collaborative filtering. """
cf_recs = self.get_collaborative_filtering_recommendations(user_id, n=n*2) # Get more CF recs
cb_recs = []
if current_product_id:
cb_recs = self.get_content_based_recommendations(current_product_id, n=n*2)
# Combine and rank recommendations. This is a simplified approach.
# More advanced methods involve weighted averaging or machine learning models.
combined_recs = {}
for rec in cf_recs:
combined_recs[rec] = combined_recs.get(rec, 0) + 1 # Simple count
for rec in cb_recs:
combined_recs[rec] = combined_recs.get(rec, 0) + 1 # Simple count
# Filter out items the user has already purchased (requires purchase history)
# purchased_items = self.user_interactions_df[
# (self.user_interactions_df['user_id'] == user_id) &
# (self.user_interactions_df['interaction_type'] == 'purchase')
# ]['product_id'].tolist()
# combined_recs = {k: v for k, v in combined_recs.items() if k not in purchased_items}
sorted_hybrid_recs = sorted(combined_recs.items(), key=lambda item: item[1], reverse=True)
return [item[0] for item in sorted_hybrid_recs[:n]]
# Example DataFrames (simplified)
# products_data = {'product_id': ['p1', 'p2', 'p3', 'p4', 'p5'],
# 'category': ['electronics', 'books', 'electronics', 'clothing', 'books']}
# products_df = pd.DataFrame(products_data)
#
# interactions_data = {'user_id': ['u1', 'u1', 'u2', 'u2', 'u2', 'u3', 'u3', 'u3', 'u3'],
# 'product_id': ['p1', 'p3', 'p2', 'p4', 'p5', 'p1', 'p2', 'p3', 'p5'],
# 'interaction_type': ['view', 'view', 'view', 'view', 'view', 'view', 'view', 'view', 'view']}
# user_interactions_df = pd.DataFrame(interactions_data)
#
# recommender = RecommendationEngine(products_df, user_interactions_df)
#
# # Recommendations for user u1, potentially on product p1 page
# user_recs = recommender.get_hybrid_recommendations(user_id='u1', current_product_id='p1')
# print(f"Recommendations for user u1: {user_recs}")
#
# # Recommendations for user u2
# user_recs_u2 = recommender.get_hybrid_recommendations(user_id='u2')
# print(f"Recommendations for user u2: {user_recs_u2}")
Real-time Tracking and API Endpoint
A JavaScript snippet on the e-commerce site would capture user events and send them to a backend API. This API would update user profiles and potentially trigger near real-time model updates or cache invalidations. The recommendations would then be served via another API endpoint.
// Frontend JavaScript snippet (to be embedded on e-commerce site)
function trackEvent(userId, productId, eventType) {
fetch('/api/track-event', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId, productId, eventType, timestamp: Date.now() })
}).catch(error => console.error('Error tracking event:', error));
}
// Example usage on product page:
// Assuming userId and productId are available from the page context
// trackEvent(userId, productId, 'view');
// Example usage on add-to-cart button click:
// document.getElementById('add-to-cart-btn').addEventListener('click', () => {
// trackEvent(userId, productId, 'add_to