Guides and Examples
...
Orders
Fetch Orders
20 min
this guide provides comprehensive instructions for retrieving order data using the nue lifecycle management api learn how to fetch customer orders, filter by status, include related data, and implement efficient order retrieval patterns prerequisites before you begin, ensure you have a valid nue api key with order read permissions customer ids for the orders you want to retrieve basic understanding of rest apis and json familiarity with order data structures and lifecycle authentication all order retrieval 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"); basic order retrieval fetch all orders for customer try it now fetch orders ā https //api docs nue io/fetch orders const myheaders = new headers(); myheaders append("nue api key", "your api key here"); myheaders append("content type", "application/json"); // fetch all orders for a customer const customerids = \["d2e04653 ae90 49df a986 134cf64f6d03"]; const encodedcustomerids = encodeuricomponent(json stringify(customerids)); fetch(`https //api nue io/orders?customerids=${encodedcustomerids}`, { method 'get', headers myheaders }) then(response => response json()) then(result => { console log('orders retrieved successfully ', result); if (result status === 'success' && result data) { console log(`found orders for customer`); // display order summary console log('\nš order summary '); console log(`customer id ${customerids\[0]}`); console log(`total orders ${result data length || 0}`); // display each order if (result data length > 0) { result data foreach((order, index) => { console log(`\n${index + 1} order ${order ordernumber}`); console log(` id ${order id}`); console log(` status ${order status}`); console log(` total $${order grandtotal || order nettotal}`); console log(` date ${order orderstartdate || order createddate}`); console log(` type ${order ordertype || 'standard'}`); }); } } }) catch(error => console log('error ', error)); fetch orders for multiple customers retrieve orders for multiple customers in a single api call // fetch orders for multiple customers const customerids = \[ "d2e04653 ae90 49df a986 134cf64f6d03", "cc5e1f0f 5e14 48cc ab98 9e5b191aa46f", "f1b2c3d4 e5f6 7890 abcd ef1234567890" ]; const encodedcustomerids = encodeuricomponent(json stringify(customerids)); fetch(`https //api nue io/orders?customerids=${encodedcustomerids}`, { method 'get', headers myheaders }) then(response => response json()) then(result => { if (result status === 'success') { console log(`retrieved orders for ${customerids length} customers`); // group orders by customer const ordersbycustomer = {}; if (result data && array isarray(result data)) { result data foreach(order => { const customerid = order customerid; if (!ordersbycustomer\[customerid]) { ordersbycustomer\[customerid] = \[]; } ordersbycustomer\[customerid] push(order); }); } // display grouped results object keys(ordersbycustomer) foreach(customerid => { const orders = ordersbycustomer\[customerid]; console log(`\n customer ${customerid} `); console log(`orders ${orders length}`); orders foreach(order => { console log(` ⢠${order ordernumber} ${order status} $${order grandtotal || order nettotal}`); }); }); } }) catch(error => console log('error ', error)); filtered order retrieval fetch active orders only filter orders by status to retrieve only active orders const customerids = \["d2e04653 ae90 49df a986 134cf64f6d03"]; const encodedcustomerids = encodeuricomponent(json stringify(customerids)); // fetch only active orders const url = `https //api nue io/orders?customerids=${encodedcustomerids}\&status=activated`; fetch(url, { method 'get', headers myheaders }) then(response => response json()) then(result => { if (result status === 'success') { console log('š¢ active orders retrieved'); if (result data && result data length > 0) { result data foreach(order => { console log(`\nš¦ ${order ordernumber}`); console log(` status ${order status}`); console log(` activated ${order activateddate || 'n/a'}`); console log(` value $${order grandtotal}`); console log(` next billing ${order nextbillingdate || 'n/a'}`); // show subscription details if available if (order subscriptionenddate) { console log(` subscription end ${order subscriptionenddate}`); } }); } else { console log('no active orders found for this customer'); } } }) catch(error => console log('error ', error)); fetch draft orders only retrieve draft orders that are pending activation const draftordersurl = `https //api nue io/orders?customerids=${encodedcustomerids}\&status=draft`; fetch(draftordersurl, { method 'get', headers myheaders }) then(response => response json()) then(result => { if (result status === 'success') { console log('š draft orders retrieved'); if (result data && result data length > 0) { result data foreach(order => { console log(`\nš ${order ordernumber || order id}`); console log(` status ${order status}`); console log(` created ${order createddate}`); console log(` value $${order grandtotal}`); console log(` ready for activation ${order readyforactivation ? 'yes' 'no'}`); }); console log(`\nš” ${result data length} draft orders ready for activation`); } else { console log('no draft orders found for this customer'); } } }) catch(error => console log('error ', error)); including related data fetch orders with product details include order products in the response for detailed analysis const customerids = \["d2e04653 ae90 49df a986 134cf64f6d03"]; const encodedids = encodeuricomponent(json stringify(customerids)); // include order products in the response const urlwithproducts = `https //api nue io/orders?customerids=${encodedids}\&includes=orderproducts`; fetch(urlwithproducts, { method 'get', headers myheaders }) then(response => response json()) then(result => { if (result status === 'success' && result data) { result data foreach(order => { console log(`\nš¦ order ${order ordernumber}`); console log(` status ${order status}`); console log(` total $${order grandtotal}`); // display order products if (order orderproducts && order orderproducts length > 0) { console log(`\n products (${order orderproducts length}) `); order orderproducts foreach(product => { console log(` ⢠${product productname || product description}`); console log(` quantity ${product quantity}`); console log(` unit price $${product unitprice || 'n/a'}`); console log(` total $${product totalprice || 'n/a'}`); if (product subscriptionterm) { console log(` term ${product subscriptionterm} months`); } if (product startdate && product enddate) { console log(` period ${product startdate} to ${product enddate}`); } }); } else { console log(' no product details available'); } }); } }) catch(error => console log('error ', error)); fetch orders with assets and invoices include complete order ecosystem data // include multiple related data types const urlwithall = `https //api nue io/orders?customerids=${encodedids}\&includes=orderproducts,assets,invoices`; fetch(urlwithall, { method 'get', headers myheaders }) then(response => response json()) then(result => { if (result status === 'success' && result data) { result data foreach(order => { console log(`\nšÆ complete order details ${order ordernumber}`); console log(` status ${order status}`); console log(` customer ${order customername || order customerid}`); console log(` total value $${order grandtotal}`); // order products if (order orderproducts && order orderproducts length > 0) { console log(`\n š order lines ${order orderproducts length}`); order orderproducts foreach((product, idx) => { console log(` ${idx + 1} ${product productname} (qty ${product quantity})`); }); } // assets created if (order assets && order assets length > 0) { console log(`\n šļø assets ${order assets length}`); order assets foreach(asset => { console log(` ⢠${asset productname} ${asset status}`); console log(` period ${asset startdate} to ${asset enddate}`); console log(` quantity ${asset quantity}`); }); } // invoices generated if (order invoices && order invoices length > 0) { console log(`\n š° invoices ${order invoices length}`); order invoices foreach(invoice => { console log(` ⢠${invoice invoicenumber || invoice id} $${invoice amount}`); console log(` status ${invoice status}`); console log(` due ${invoice duedate}`); console log(` balance $${invoice balance}`); }); } }); } }) catch(error => console log('error ', error)); advanced order analysis order portfolio analysis service build comprehensive order analytics and insights class orderanalysisservice { constructor(apikey) { this apikey = apikey; this headers = new headers(); this headers append("nue api key", apikey); this headers append("content type", "application/json"); } async analyzecustomerorders(customerid, options = {}) { try { // fetch comprehensive order data const orders = await this fetchorderswithdetails(\[customerid], options); if (!orders || orders length === 0) { return { customerid, totalorders 0, message 'no orders found for customer' }; } // perform analysis const analysis = this performorderanalysis(orders); // generate insights const insights = this generateinsights(analysis); return { customerid, analysis, insights, orders options includeorderdetails ? orders undefined }; } catch (error) { console error(`order analysis failed for customer ${customerid} `, error); return { customerid, error error message }; } } async fetchorderswithdetails(customerids, options = {}) { const encodedids = encodeuricomponent(json stringify(customerids)); // build url with includes const includes = \['orderproducts', 'assets', 'invoices']; const includesstr = includes join(','); const url = `https //api nue io/orders?customerids=${encodedids}\&includes=${includesstr}`; const response = await fetch(url, { method 'get', headers this headers }); if (!response ok) { throw new error(`failed to fetch orders ${response status}`); } const result = await response json(); if (result status !== 'success') { throw new error(`api error ${result message || 'unknown error'}`); } return result data || \[]; } performorderanalysis(orders) { const analysis = { overview { totalorders orders length, ordersbystatus {}, ordersbytype {}, totalvalue 0, averageordervalue 0 }, timeline { firstorder null, lastorder null, orderfrequency 0 }, products { uniqueproducts new set(), topproducts {}, totalassets 0, activeassets 0 }, financial { totalinvoiced 0, totalpaid 0, outstandingbalance 0, invoicesbystatus {} }, subscription { activesubscriptions 0, subscriptionvalue 0, averagesubscriptionlength 0, renewaldates \[] } }; let totalsublength = 0; let subcount = 0; orders foreach(order => { // overview analysis analysis overview\ totalvalue += (order grandtotal || order nettotal || 0); const status = order status || 'unknown'; analysis overview\ ordersbystatus\[status] = (analysis overview\ ordersbystatus\[status] || 0) + 1; const type = order ordertype || 'standard'; analysis overview\ ordersbytype\[type] = (analysis overview\ ordersbytype\[type] || 0) + 1; // timeline analysis const orderdate = new date(order orderstartdate || order createddate); if (!analysis timeline firstorder || orderdate < new date(analysis timeline firstorder)) { analysis timeline firstorder = order orderstartdate || order createddate; } if (!analysis timeline lastorder || orderdate > new date(analysis timeline lastorder)) { analysis timeline lastorder = order orderstartdate || order createddate; } // product analysis if (order orderproducts) { order orderproducts foreach(product => { const productname = product productname || product description; if (productname) { analysis products uniqueproducts add(productname); analysis products topproducts\[productname] = (analysis products topproducts\[productname] || 0) + (product quantity || 1); } }); } // asset analysis if (order assets) { analysis products totalassets += order assets length; analysis products activeassets += order assets filter(a => a status === 'active') length; // subscription analysis order assets foreach(asset => { if (asset status === 'active' && asset enddate) { analysis subscription activesubscriptions++; analysis subscription subscriptionvalue += (asset recurringrevenue || 0); analysis subscription renewaldates push(asset enddate); if (asset startdate && asset enddate) { const start = new date(asset startdate); const end = new date(asset enddate); const lengthmonths = math round((end start) / (1000 60 60 24 30)); totalsublength += lengthmonths; subcount++; } } }); } // financial analysis if (order invoices) { order invoices foreach(invoice => { analysis financial totalinvoiced += (invoice amount || 0); analysis financial outstandingbalance += (invoice balance || 0); analysis financial totalpaid += ((invoice amount || 0) (invoice balance || 0)); const invoicestatus = invoice status || 'unknown'; analysis financial invoicesbystatus\[invoicestatus] = (analysis financial invoicesbystatus\[invoicestatus] || 0) + 1; }); } }); // calculate derived metrics analysis overview\ averageordervalue = analysis overview\ totalorders > 0 ? analysis overview\ totalvalue / analysis overview\ totalorders 0; analysis subscription averagesubscriptionlength = subcount > 0 ? totalsublength / subcount 0; // calculate order frequency (orders per year) if (analysis timeline firstorder && analysis timeline lastorder) { const firstdate = new date(analysis timeline firstorder); const lastdate = new date(analysis timeline lastorder); const yearsdiff = (lastdate firstdate) / (1000 60 60 24 365); analysis timeline orderfrequency = yearsdiff > 0 ? analysis overview\ totalorders / yearsdiff 0; } // convert set to array for json serialization analysis products uniqueproducts = array from(analysis products uniqueproducts); return analysis; } generateinsights(analysis) { const insights = \[]; // order volume insights if (analysis overview\ totalorders === 0) { insights push({ type 'warning', category 'orders', message 'no orders found for this customer' }); } else if (analysis overview\ totalorders === 1) { insights push({ type 'info', category 'orders', message 'single order customer potential for growth' }); } else if (analysis overview\ totalorders >= 10) { insights push({ type 'positive', category 'orders', message 'high volume customer with strong order history' }); } // order value insights if (analysis overview\ averageordervalue > 50000) { insights push({ type 'positive', category 'revenue', message 'high value customer with large average order size' }); } else if (analysis overview\ averageordervalue < 1000) { insights push({ type 'warning', category 'revenue', message 'low average order value consider upselling opportunities' }); } // status insights const draftorders = analysis overview\ ordersbystatus\['draft'] || 0; if (draftorders > 0) { insights push({ type 'action', category 'orders', message `${draftorders} draft orders pending activation` }); } // financial insights if (analysis financial outstandingbalance > 0) { insights push({ type 'warning', category 'finance', message `outstanding balance $${analysis financial outstandingbalance tolocalestring()}` }); } // subscription insights if (analysis subscription activesubscriptions > 0) { const nextrenewal = analysis subscription renewaldates sort() find(date => new date(date) > new date()); if (nextrenewal) { const daystorenewal = math ceil((new date(nextrenewal) new date()) / (1000 60 60 24)); if (daystorenewal <= 30) { insights push({ type 'action', category 'subscription', message `subscription renewal due in ${daystorenewal} days` }); } } } // product insights if (analysis products uniqueproducts length === 1) { insights push({ type 'opportunity', category 'products', message 'single product customer consider cross selling' }); } else if (analysis products uniqueproducts length >= 5) { insights push({ type 'positive', category 'products', message 'diverse product portfolio customer' }); } return insights; } async generateorderreport(customerids, options = {}) { console log(`\nš generating order report for ${customerids length} customers `); const reports = \[]; for (const customerid of customerids) { const analysis = await this analyzecustomerorders(customerid, options); reports push(analysis); // display individual customer report this displaycustomerreport(analysis); } // generate summary report this displaysummaryreport(reports); return reports; } displaycustomerreport(analysis) { if (analysis error) { console log(`\nā ${analysis customerid} ${analysis error}`); return; } console log(`\nš customer ${analysis customerid}`); console log('=' repeat(50)); const a = analysis analysis; // overview console log(`\nš overview `); console log(` total orders ${a overview\ totalorders}`); console log(` total value $${a overview\ totalvalue tolocalestring()}`); console log(` average order $${a overview\ averageordervalue tolocalestring()}`); console log(` order frequency ${a timeline orderfrequency tofixed(1)} orders/year`); // status breakdown console log(`\nš order status `); object entries(a overview\ ordersbystatus) foreach((\[status, count]) => { console log(` ${status} ${count}`); }); // products console log(`\nš¦ products `); console log(` unique products ${a products uniqueproducts length}`); console log(` total assets ${a products totalassets} (${a products activeassets} active)`); // subscriptions if (a subscription activesubscriptions > 0) { console log(`\nš subscriptions `); console log(` active ${a subscription activesubscriptions}`); console log(` monthly value $${a subscription subscriptionvalue tolocalestring()}`); console log(` avg length ${a subscription averagesubscriptionlength tofixed(1)} months`); } // financial console log(`\nš° financial `); console log(` total invoiced $${a financial totalinvoiced tolocalestring()}`); console log(` total paid $${a financial totalpaid tolocalestring()}`); console log(` outstanding $${a financial outstandingbalance tolocalestring()}`); // insights if (analysis insights && analysis insights length > 0) { console log(`\nš” insights `); analysis insights foreach(insight => { const icon = insight type === 'positive' ? 'ā
' insight type === 'warning' ? 'ā ļø' insight type === 'action' ? 'šÆ' 'ā¹ļø'; console log(` ${icon} ${insight message}`); }); } } displaysummaryreport(reports) { console log(`\nš summary report`); console log('=' repeat(50)); const validreports = reports filter(r => !r error); const totalcustomers = validreports length; if (totalcustomers === 0) { console log('no valid customer data found'); return; } const totals = validreports reduce((acc, r) => { const a = r analysis; return { orders acc orders + a overview\ totalorders, value acc value + a overview\ totalvalue, assets acc assets + a products totalassets, activeassets acc activeassets + a products activeassets, subscriptions acc subscriptions + a subscription activesubscriptions }; }, { orders 0, value 0, assets 0, activeassets 0, subscriptions 0 }); console log(`\nš portfolio summary `); console log(` total customers ${totalcustomers}`); console log(` total orders ${totals orders}`); console log(` total value $${totals value tolocalestring()}`); console log(` avg per customer $${(totals value / totalcustomers) tolocalestring()}`); console log(` total assets ${totals assets} (${totals activeassets} active)`); console log(` active subscriptions ${totals subscriptions}`); } } // usage examples const orderanalysis = new orderanalysisservice("your api key here"); // single customer analysis const singleanalysis = await orderanalysis analyzecustomerorders( "d2e04653 ae90 49df a986 134cf64f6d03", { includeorderdetails false } ); console log('customer analysis completed'); // multi customer report const customerids = \[ "d2e04653 ae90 49df a986 134cf64f6d03", "cc5e1f0f 5e14 48cc ab98 9e5b191aa46f" ]; const reports = await orderanalysis generateorderreport(customerids); console log(`portfolio analysis completed for ${customerids length} customers`); query parameters reference parameter type required description options customerids array\[string] yes json encoded array of customer ids \["customer uuid 1", "customer uuid 2"] status string no filter orders by status "activated" , "draft" , "canceled" includes string no related data to include "orderproducts" , "assets" , "invoices" response structure success response (200 ok) { "status" "success", "data" \[ { "id" "order uuid", "ordernumber" "ord 000001", "customerid" "customer uuid", "customername" "customer name", "status" "active", "orderstartdate" "2025 01 01", "activateddate" "2025 01 01t10 30 00z", "grandtotal" 9720 00, "nettotal" 9000 00, "ordertype" "new", "orderproducts" \[], "assets" \[], "invoices" \[] } ] } error handling common retrieval errors error description resolution invalid customer id customer id format invalid verify customer id format customer not found customer does not exist check customer id exists invalid status filter invalid status value use valid status values invalid includes invalid include parameter check available include options robust order fetching async function safeorderfetch(customerids, options = {}) { try { // validate inputs if (!array isarray(customerids) || customerids length === 0) { throw new error('customerids must be a non empty array'); } const encodedids = encodeuricomponent(json stringify(customerids)); let url = `https //api nue io/orders?customerids=${encodedids}`; // add optional parameters if (options status) { url += `\&status=${options status}`; } if (options includes) { url += `\&includes=${options includes}`; } const response = await fetch(url, { method 'get', headers myheaders }); if (!response ok) { throw new error(`http ${response status} ${response statustext}`); } const result = await response json(); if (result status !== 'success') { throw new error(`api error ${result message || 'unknown error'}`); } return { orders result data || \[], found result data? length || 0, requested customerids length }; } catch (error) { console error('order fetch error ', error); return { orders \[], found 0, requested customerids length, error error message }; } } best practices data retrieval use specific status filters to reduce data transfer include related data only when needed to optimize performance batch customer queries efficiently cache frequently accessed order data performance optimization limit includes to required data only implement pagination for large result sets use appropriate timeout settings for api calls monitor api usage and respect rate limits business intelligence analyze order patterns for customer insights track subscription renewals proactively monitor order status transitions generate actionable insights from order data this comprehensive guide enables you to efficiently retrieve and analyze order data using the nue lifecycle management api, supporting everything from simple order lookups to complex portfolio analysis and business intelligence operations