Guides and Examples
...
Price and Discount Tags
Fetching Price and Discount Tags
21 min
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 → https //api docs nue io/fetch price tag 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(tagids) { try { console log('🏷️ building tag catalog '); // fetch all tags const encodedids = encodeuricomponent(json stringify(tagids)); const response = await fetch( `https //api nue io/pricediscounttags?pricediscounttagids=${encodedids}`, { 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"); const tagids = \[ "price tag uuid 1", "discount tag uuid 2", "price tag uuid 3", "discount tag uuid 4" ]; tagmanager buildtagcatalog(tagids) 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(tagids) { try { const encodedids = encodeuricomponent(json stringify(tagids)); const response = await fetch( `https //api nue io/pricediscounttags?pricediscounttagids=${encodedids}`, { 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(tagids) 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(tagids, pricingcontext) { try { console log('⚡ calculating dynamic pricing '); // fetch relevant tags const encodedids = encodeuricomponent(json stringify(tagids)); const response = await fetch( `https //api nue io/pricediscounttags?pricediscounttagids=${encodedids}`, { 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(tagids, pricingcontext) then(pricingresult => { console log('dynamic pricing calculation completed'); }); error handling and best practices robust tag fetching async function safetagfetch(tagids, options = {}) { const myheaders = new headers(); myheaders append("nue api key", "your api key here"); myheaders append("content type", "application/json"); try { // validate input if (!array isarray(tagids) || tagids length === 0) { throw new error('tag ids must be a non empty array'); } // validate tag id formats (basic uuid validation) const uuidregex = /^\[0 9a f]{8} \[0 9a f]{4} \[1 5]\[0 9a f]{3} \[89ab]\[0 9a f]{3} \[0 9a f]{12}$/i; const invalidids = tagids filter(id => !uuidregex test(id)); if (invalidids length > 0) { console warn('invalid tag id formats detected ', invalidids); } const validids = tagids filter(id => uuidregex test(id)); if (validids length === 0) { throw new error('no valid tag ids provided'); } const encodedids = encodeuricomponent(json stringify(validids)); const response = await fetch( `https //api nue io/pricediscounttags?pricediscounttagids=${encodedids}`, { 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'); } // check for missing tags const foundids = tags map(tag => tag id); const missingids = validids filter(id => !foundids includes(id)); return { tags, found tags length, requested validids length, missing missingids, invalid invalidids }; } catch (error) { console error('tag fetch error ', error); return { tags \[], found 0, requested tagids length, missing tagids, invalid \[], error error message }; } } // usage with error handling safetagfetch(\[ "valid tag uuid 1", "invalid tag id", "valid tag uuid 2" ]) then(result => { if (result error) { console error('fetch failed ', result error); } else { console log(`successfully fetched ${result found}/${result requested} tags`); if (result missing length > 0) { console log('missing tags ', result missing); } if (result invalid length > 0) { console log('invalid tag ids ', result invalid); } } }); query parameters reference parameter type required description example pricediscounttagids array\[string] yes json encoded array of tag ids \["tag uuid 1", "tag uuid 2"] 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(alltagids); // generate strategic recommendations dynamic pricing engine // calculate real time pricing based on context const pricing = await pricingengine calculatedynamicpricing(tagids, context); // apply pricing to orders or quotes tag catalog management // build comprehensive tag catalog const catalog = await tagmanager buildtagcatalog(tagids); // enable search and filtering features performance 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 1000 requests per minute in production 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