Fetching Price and Discount Tags
This guide provides comprehensive instructions for retrieving price and discount tags using the Nue Lifecycle Management API. Learn how to fetch all tags or individual tags by code, and implement efficient tag-based pricing workflows.
Prerequisites
Before you begin, ensure you have:
- A valid Nue API key
- Price tag codes for individual lookups
- Basic understanding of REST APIs and JSON
- Familiarity with price and discount tag structures
Authentication
All tag operations require authentication using your Nue API key in the nue-api-key header:
const myHeaders = new Headers();
myHeaders.append("nue-api-key", "YOUR_API_KEY_HERE");
myHeaders.append("Content-Type", "application/json");Tag Retrieval Methods
Fetch All Price Tags
Try it now: Fetch Price and Discount Tags →
const myHeaders = new Headers();
myHeaders.append("nue-api-key", "YOUR_API_KEY_HERE");
myHeaders.append("Content-Type", "application/json");
// Fetch all published price tags
fetch("https://api.nue.io/catalog/price-tags", {
method: 'GET',
headers: myHeaders
})
.then(response => response.json())
.then(tags => {
console.log(`Retrieved ${tags.length} price and discount tags`);
tags.forEach(tag => {
console.log(`\n--- ${tag.name} ---`);
console.log(`ID: ${tag.id}`);
console.log(`Code: ${tag.code}`);
console.log(`Type: ${tag.priceTagType}`);
console.log(`Status: ${tag.active ? 'Active' : 'Inactive'}`);
console.log(`Description: ${tag.description || 'No description'}`);
// Display pricing tiers
if (tag.priceTiers && tag.priceTiers.length > 0) {
console.log('Pricing Tiers:');
tag.priceTiers.forEach((tier, index) => {
console.log(` Tier ${index + 1}:`);
console.log(` Range: ${tier.startUnit || 0} - ${tier.endUnit || '∞'}`);
console.log(` Charge Model: ${tier.chargeModel}`);
if (tier.discountPercentage) {
console.log(` Discount: ${tier.discountPercentage}%`);
}
if (tier.amount) {
console.log(` Amount: $${tier.amount}`);
}
});
}
// Display date ranges
if (tag.startTime) {
console.log(`Effective: ${tag.startTime} to ${tag.endTime || 'No end date'}`);
}
});
})
.catch(error => console.log('Error:', error));Fetch Single Price Tag by Code
Retrieve a specific price tag using its code:
const priceTagCode = "FFT";
fetch(`https://api.nue.io/catalog/price-tags/${priceTagCode}`, {
method: 'GET',
headers: myHeaders
})
.then(response => response.json())
.then(result => {
const tag = result[0]; // API returns array even for single price tag
if (tag) {
console.log('✅ Price tag found:');
console.log(`Name: ${tag.name}`);
console.log(`Code: ${tag.code}`);
console.log(`ID: ${tag.id}`);
console.log(`Active: ${tag.active}`);
console.log(`Price Type: ${tag.priceType}`);
console.log(`Publish Status: ${tag.publishStatus}`);
// Display pricing tiers
if (tag.priceTiers && tag.priceTiers.length > 0) {
console.log('Pricing Tiers:');
tag.priceTiers.forEach((tier, index) => {
console.log(` Tier ${index + 1}:`);
console.log(` Range: ${tier.startUnit || 0} - ${tier.endUnit || '∞'}`);
console.log(` Charge Model: ${tier.chargeModel}`);
if (tier.discountPercentage) {
console.log(` Discount: ${tier.discountPercentage}%`);
}
if (tier.amount) {
console.log(` Amount: $${tier.amount}`);
}
});
}
} else {
console.log('❌ Price tag not found or not published');
}
})
.catch(error => console.log('Error:', error));Advanced Tag Retrieval Patterns
Tag Catalog Manager
Build a comprehensive tag management system with advanced filtering and categorization:
class TagCatalogManager {
constructor(apiKey) {
this.apiKey = apiKey;
this.headers = new Headers();
this.headers.append("nue-api-key", apiKey);
this.headers.append("Content-Type", "application/json");
this.tagCache = new Map();
}
async buildTagCatalog() {
try {
console.log('🏷️ Building tag catalog...');
// Fetch all published tags
const response = await fetch(
`https://api.nue.io/catalog/price-tags`,
{
method: 'GET',
headers: this.headers
}
);
if (!response.ok) {
throw new Error(`Failed to fetch tags: ${response.status}`);
}
const tags = await response.json();
// Build comprehensive catalog
const catalog = {
priceTag: [],
discountTags: [],
byType: {},
byCurrency: {},
byStatus: { active: [], inactive: [] },
statistics: {
totalTags: tags.length,
activeTags: 0,
inactiveTags: 0,
priceTagsCount: 0,
discountTagsCount: 0,
currencies: new Set()
}
};
tags.forEach(tag => {
// Categorize by main type
if (tag.type === 'Price') {
catalog.priceTag.push(tag);
catalog.statistics.priceTagsCount++;
} else if (tag.type === 'Discount') {
catalog.discountTags.push(tag);
catalog.statistics.discountTagsCount++;
}
// Categorize by sub-type
const subType = tag.priceType || tag.discountType;
if (subType) {
if (!catalog.byType[subType]) {
catalog.byType[subType] = [];
}
catalog.byType[subType].push(tag);
}
// Categorize by currency
if (tag.currency) {
if (!catalog.byCurrency[tag.currency]) {
catalog.byCurrency[tag.currency] = [];
}
catalog.byCurrency[tag.currency].push(tag);
catalog.statistics.currencies.add(tag.currency);
}
// Categorize by status
if (tag.isActive) {
catalog.byStatus.active.push(tag);
catalog.statistics.activeTags++;
} else {
catalog.byStatus.inactive.push(tag);
catalog.statistics.inactiveTags++;
}
// Cache tag for quick lookup
this.tagCache.set(tag.id, tag);
});
// Display catalog summary
console.log('\n📊 Tag Catalog Summary:');
console.log(` Total Tags: ${catalog.statistics.totalTags}`);
console.log(` Price Tags: ${catalog.statistics.priceTagsCount}`);
console.log(` Discount Tags: ${catalog.statistics.discountTagsCount}`);
console.log(` Active: ${catalog.statistics.activeTags}`);
console.log(` Inactive: ${catalog.statistics.inactiveTags}`);
console.log(` Currencies: ${Array.from(catalog.statistics.currencies).join(', ')}`);
console.log(`\n🏷️ Tags by Type:`);
Object.entries(catalog.byType)
.sort(([,a], [,b]) => b.length - a.length)
.forEach(([type, tags]) => {
console.log(` ${type}: ${tags.length} tags`);
});
return catalog;
} catch (error) {
console.error('Failed to build tag catalog:', error);
throw error;
}
}
searchTags(catalog, searchTerm) {
const term = searchTerm.toLowerCase();
const allTags = [...catalog.priceTag, ...catalog.discountTags];
return allTags.filter(tag => {
return tag.name?.toLowerCase().includes(term) ||
tag.description?.toLowerCase().includes(term) ||
tag.type?.toLowerCase().includes(term) ||
tag.priceType?.toLowerCase().includes(term) ||
tag.discountType?.toLowerCase().includes(term);
});
}
getActiveTagsForCurrency(catalog, currency) {
return catalog.byCurrency[currency]?.filter(tag => tag.isActive) || [];
}
getTagsByType(catalog, type) {
return catalog.byType[type] || [];
}
getEffectiveTagsForDate(catalog, targetDate) {
const target = new Date(targetDate);
const allTags = [...catalog.priceTag, ...catalog.discountTags];
return allTags.filter(tag => {
if (!tag.isActive) return false;
const startDate = tag.effectiveStartDate ? new Date(tag.effectiveStartDate) : null;
const endDate = tag.effectiveEndDate ? new Date(tag.effectiveEndDate) : null;
if (startDate && target < startDate) return false;
if (endDate && target > endDate) return false;
return true;
});
}
}
// Usage
const tagManager = new TagCatalogManager("YOUR_API_KEY_HERE");
tagManager.buildTagCatalog()
.then(catalog => {
console.log('\n🏷️ Tag catalog built successfully');
// Search example
const searchResults = tagManager.searchTags(catalog, 'enterprise');
console.log(`\n🔍 Search for "enterprise": ${searchResults.length} results`);
// Get active USD tags
const usdTags = tagManager.getActiveTagsForCurrency(catalog, 'USD');
console.log(`\n💰 Active USD tags: ${usdTags.length} tags`);
// Get effective tags for today
const effectiveTags = tagManager.getEffectiveTagsForDate(catalog, new Date());
console.log(`\n📅 Tags effective today: ${effectiveTags.length} tags`);
return catalog;
});Pricing Strategy Analyzer
Analyze pricing and discount strategies using tag data:
class PricingStrategyAnalyzer {
constructor(apiKey) {
this.apiKey = apiKey;
this.headers = new Headers();
this.headers.append("nue-api-key", apiKey);
this.headers.append("Content-Type", "application/json");
}
async analyzePricingStrategy() {
try {
const response = await fetch(
`https://api.nue.io/catalog/price-tags`,
{
method: 'GET',
headers: this.headers
}
);
if (!response.ok) {
throw new Error(`Failed to fetch tags: ${response.status}`);
}
const tags = await response.json();
// Analyze pricing strategy
const analysis = {
pricing: {
strategies: {},
currencies: {},
priceRanges: {},
averagePrices: {}
},
discounts: {
types: {},
percentageRanges: {},
averageDiscounts: {},
seasonalPatterns: []
},
recommendations: []
};
// Analyze price tags
const priceTags = tags.filter(tag => tag.type === 'Price');
const discountTags = tags.filter(tag => tag.type === 'Discount');
console.log('\n💰 Pricing Strategy Analysis');
console.log('==============================');
// Price analysis
priceTags.forEach(tag => {
// Group by price type
if (!analysis.pricing.strategies[tag.priceType]) {
analysis.pricing.strategies[tag.priceType] = [];
}
analysis.pricing.strategies[tag.priceType].push(tag);
// Group by currency
if (!analysis.pricing.currencies[tag.currency]) {
analysis.pricing.currencies[tag.currency] = [];
}
analysis.pricing.currencies[tag.currency].push(tag);
});
// Discount analysis
discountTags.forEach(tag => {
// Group by discount type
if (!analysis.discounts.types[tag.discountType]) {
analysis.discounts.types[tag.discountType] = [];
}
analysis.discounts.types[tag.discountType].push(tag);
});
// Generate pricing insights
console.log(`\n📊 Pricing Insights:`);
console.log(` Total Price Tags: ${priceTags.length}`);
console.log(` Total Discount Tags: ${discountTags.length}`);
console.log(`\n💼 Price Strategies:`);
Object.entries(analysis.pricing.strategies).forEach(([strategy, tags]) => {
console.log(` ${strategy}: ${tags.length} tags`);
const prices = tags
.filter(tag => tag.listPrice)
.map(tag => parseFloat(tag.listPrice));
if (prices.length > 0) {
const avgPrice = prices.reduce((sum, price) => sum + price, 0) / prices.length;
const minPrice = Math.min(...prices);
const maxPrice = Math.max(...prices);
console.log(` Average: $${avgPrice.toFixed(2)}`);
console.log(` Range: $${minPrice} - $${maxPrice}`);
}
});
console.log(`\n💸 Discount Analysis:`);
Object.entries(analysis.discounts.types).forEach(([type, tags]) => {
console.log(` ${type}: ${tags.length} tags`);
const percentages = tags
.filter(tag => tag.discountPercent)
.map(tag => parseFloat(tag.discountPercent));
if (percentages.length > 0) {
const avgDiscount = percentages.reduce((sum, pct) => sum + pct, 0) / percentages.length;
const minDiscount = Math.min(...percentages);
const maxDiscount = Math.max(...percentages);
console.log(` Average: ${avgDiscount.toFixed(1)}%`);
console.log(` Range: ${minDiscount}% - ${maxDiscount}%`);
}
});
// Generate recommendations
analysis.recommendations = this.generatePricingRecommendations(analysis, tags);
console.log(`\n💡 Strategic Recommendations:`);
analysis.recommendations.forEach(rec => {
console.log(` • ${rec.category}: ${rec.recommendation}`);
});
return analysis;
} catch (error) {
console.error('Failed to analyze pricing strategy:', error);
throw error;
}
}
generatePricingRecommendations(analysis, tags) {
const recommendations = [];
// Check for currency diversity
const currencies = Object.keys(analysis.pricing.currencies);
if (currencies.length === 1) {
recommendations.push({
category: 'Currency Strategy',
recommendation: 'Consider implementing multi-currency pricing for global market expansion'
});
}
// Check for discount strategy balance
const discountTypes = Object.keys(analysis.discounts.types);
if (discountTypes.length < 2) {
recommendations.push({
category: 'Discount Strategy',
recommendation: 'Diversify discount types to include volume, seasonal, and loyalty discounts'
});
}
// Check for inactive tags
const inactiveTags = tags.filter(tag => !tag.isActive);
if (inactiveTags.length > tags.length * 0.3) {
recommendations.push({
category: 'Tag Management',
recommendation: 'High number of inactive tags detected - consider archiving or reactivating'
});
}
// Check for missing effective dates
const tagsWithoutDates = tags.filter(tag => !tag.effectiveStartDate);
if (tagsWithoutDates.length > 0) {
recommendations.push({
category: 'Date Management',
recommendation: 'Set effective date ranges for better campaign and promotion management'
});
}
return recommendations;
}
}
// Usage
const strategyAnalyzer = new PricingStrategyAnalyzer("YOUR_API_KEY_HERE");
strategyAnalyzer.analyzePricingStrategy()
.then(analysis => {
console.log('Pricing strategy analysis completed');
});Tag-Based Product Pricing
Implement dynamic pricing using tag-based strategies:
class TagBasedPricingEngine {
constructor(apiKey) {
this.apiKey = apiKey;
this.headers = new Headers();
this.headers.append("nue-api-key", apiKey);
this.headers.append("Content-Type", "application/json");
}
async calculateDynamicPricing(pricingContext) {
try {
console.log('⚡ Calculating dynamic pricing...');
// Fetch relevant tags
const response = await fetch(
`https://api.nue.io/catalog/price-tags`,
{
method: 'GET',
headers: this.headers
}
);
if (!response.ok) {
throw new Error(`Failed to fetch pricing tags: ${response.status}`);
}
const tags = await response.json();
// Filter applicable tags based on context
const applicableTags = this.filterApplicableTags(tags, pricingContext);
// Calculate pricing
const pricingResult = {
basePricing: this.calculateBasePricing(applicableTags, pricingContext),
discounts: this.calculateDiscounts(applicableTags, pricingContext),
finalPricing: {},
appliedTags: applicableTags.map(tag => ({
id: tag.id,
name: tag.name,
type: tag.type,
impact: this.calculateTagImpact(tag, pricingContext)
}))
};
// Calculate final pricing
pricingResult.finalPricing = this.calculateFinalPricing(
pricingResult.basePricing,
pricingResult.discounts
);
// Display pricing breakdown
console.log('\n💰 Dynamic Pricing Calculation');
console.log('===============================');
console.log(`\n📋 Pricing Context:`);
console.log(` Customer Segment: ${pricingContext.customerSegment}`);
console.log(` Order Quantity: ${pricingContext.quantity}`);
console.log(` Currency: ${pricingContext.currency}`);
console.log(` Date: ${pricingContext.effectiveDate}`);
console.log(`\n💵 Base Pricing:`);
Object.entries(pricingResult.basePricing).forEach(([currency, price]) => {
console.log(` ${currency}: ${price.toFixed(2)}`);
});
console.log(`\n💸 Applied Discounts:`);
pricingResult.discounts.forEach(discount => {
console.log(` ${discount.name}: -${discount.amount.toFixed(2)} (${discount.type})`);
});
console.log(`\n🎯 Final Pricing:`);
Object.entries(pricingResult.finalPricing).forEach(([currency, price]) => {
console.log(` ${currency}: ${price.toFixed(2)}`);
});
console.log(`\n🏷️ Applied Tags (${pricingResult.appliedTags.length}):`);
pricingResult.appliedTags.forEach(tag => {
console.log(` • ${tag.name} (${tag.type}) - Impact: ${tag.impact}`);
});
return pricingResult;
} catch (error) {
console.error('Failed to calculate dynamic pricing:', error);
throw error;
}
}
filterApplicableTags(tags, context) {
const targetDate = new Date(context.effectiveDate);
return tags.filter(tag => {
// Must be active
if (!tag.isActive) return false;
// Must be within effective date range
if (tag.effectiveStartDate) {
const startDate = new Date(tag.effectiveStartDate);
if (targetDate < startDate) return false;
}
if (tag.effectiveEndDate) {
const endDate = new Date(tag.effectiveEndDate);
if (targetDate > endDate) return false;
}
// Must match currency if specified
if (tag.currency && tag.currency !== context.currency) return false;
return true;
});
}
calculateBasePricing(tags, context) {
const priceTags = tags.filter(tag => tag.type === 'Price');
const basePricing = {};
priceTags.forEach(tag => {
if (tag.currency && tag.listPrice) {
if (!basePricing[tag.currency] || tag.listPrice > basePricing[tag.currency]) {
basePricing[tag.currency] = parseFloat(tag.listPrice);
}
}
});
// Apply quantity-based pricing if applicable
Object.keys(basePricing).forEach(currency => {
if (context.quantity && context.quantity > 1) {
// Apply volume pricing logic here
basePricing[currency] *= context.quantity;
}
});
return basePricing;
}
calculateDiscounts(tags, context) {
const discountTags = tags.filter(tag => tag.type === 'Discount');
const discounts = [];
discountTags.forEach(tag => {
let discountAmount = 0;
let discountType = 'Unknown';
if (tag.discountPercent) {
// Percentage discount - need base price to calculate
discountType = 'Percentage';
// This would typically be calculated against the base price
} else if (tag.discountAmount) {
discountAmount = parseFloat(tag.discountAmount);
discountType = 'Fixed Amount';
}
discounts.push({
name: tag.name,
type: discountType,
amount: discountAmount,
percentage: tag.discountPercent ? parseFloat(tag.discountPercent) : 0,
tagId: tag.id
});
});
return discounts;
}
calculateFinalPricing(basePricing, discounts) {
const finalPricing = { ...basePricing };
// Apply discounts
discounts.forEach(discount => {
Object.keys(finalPricing).forEach(currency => {
if (discount.type === 'Fixed Amount') {
finalPricing[currency] -= discount.amount;
} else if (discount.type === 'Percentage') {
finalPricing[currency] *= (1 - discount.percentage / 100);
}
});
});
// Ensure no negative pricing
Object.keys(finalPricing).forEach(currency => {
finalPricing[currency] = Math.max(0, finalPricing[currency]);
});
return finalPricing;
}
calculateTagImpact(tag, context) {
if (tag.type === 'Price') {
return `Base price: ${tag.currency} ${tag.listPrice}`;
} else if (tag.type === 'Discount') {
if (tag.discountPercent) {
return `${tag.discountPercent}% discount`;
} else if (tag.discountAmount) {
return `${tag.currency} ${tag.discountAmount} discount`;
}
}
return 'Applied';
}
}
// Usage
const pricingEngine = new TagBasedPricingEngine("YOUR_API_KEY_HERE");
const pricingContext = {
customerSegment: 'Enterprise',
quantity: 5,
currency: 'USD',
effectiveDate: new Date().toISOString().split('T')[0]
};
pricingEngine.calculateDynamicPricing(pricingContext)
.then(pricingResult => {
console.log('Dynamic pricing calculation completed');
});Error Handling and Best Practices
Robust Tag Fetching
async function safeTagFetch(options = {}) {
const myHeaders = new Headers();
myHeaders.append("nue-api-key", "YOUR_API_KEY_HERE");
myHeaders.append("Content-Type", "application/json");
try {
const response = await fetch(
`https://api.nue.io/catalog/price-tags`,
{
method: 'GET',
headers: myHeaders,
timeout: 30000 // 30 second timeout
}
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const tags = await response.json();
// Validate response
if (!Array.isArray(tags)) {
throw new Error('Invalid response format - expected array');
}
return {
tags,
found: tags.length
};
} catch (error) {
console.error('Tag fetch error:', error);
return {
tags: [],
found: 0,
error: error.message
};
}
}
// Usage with error handling
safeTagFetch().then(result => {
if (result.error) {
console.error('Fetch failed:', result.error);
} else {
console.log(`Successfully fetched ${result.found} tags`);
}
});Query Parameters Reference
GET /catalog/price-tags takes no query parameters — it returns every published price and discount tag. To retrieve a single tag, pass its code as a path segment instead:
Path | Parameter | Description | Example |
|---|---|---|---|
/catalog/price-tags | — | Returns all published price and discount tags | — |
/catalog/price-tags/{code} | code | The tag's code, as a path segment | /catalog/price-tags/VOLUME_TIER_ENTERPRISE |
Response Structure
Price and Discount Tag Object Fields
Core Identity:
- id - Unique tag identifier (UUID)
- name - Tag name
- type - Tag type ("Price" or "Discount")
- description - Tag description
- isActive - Active status
Price Tag Specific:
- priceType - Type of price tag
- currency - Currency code
- listPrice - List price amount
- unitPrice - Unit price amount
Discount Tag Specific:
- discountType - Type of discount
- discountPercent - Discount percentage
- discountAmount - Fixed discount amount
Date Management:
- effectiveStartDate - When tag becomes effective
- effectiveEndDate - When tag expires
System Fields:
- createdDate, createdById - Creation tracking
- lastModifiedDate, lastModifiedById - Modification tracking
Common Use Cases
Pricing Strategy Analysis
// Analyze current pricing and discount strategies
const analysis = await strategyAnalyzer.analyzePricingStrategy();
// Generate strategic recommendationsDynamic Pricing Engine
// Calculate real-time pricing based on context
const pricing = await pricingEngine.calculateDynamicPricing(context);
// Apply pricing to orders or quotesTag Catalog Management
// Build comprehensive tag catalog
const catalog = await tagManager.buildTagCatalog();
// Enable search and filtering featuresPerformance Optimization
Efficient Tag Operations
- Batch tag lookups: Include multiple tag IDs in single API call
- Validate ID formats: Client-side validation before API calls
- Cache tag data: Store frequently accessed tag information
- Error recovery: Implement graceful handling of missing tags
Rate Limiting
- Respect limits: Rate limits apply; contact Nue support to confirm your limits or request an increase
- Implement backoff: Use exponential backoff for retry logic
- Monitor usage: Track API consumption patterns
This comprehensive guide enables you to efficiently retrieve and manage price and discount tag data using the Nue Lifecycle Management API, supporting everything from simple tag lookups to complex pricing strategy analysis and dynamic pricing calculations.