price_api/sql/guidance.pg.sql

43 lines
1.2 KiB
SQL

CREATE OR REPLACE FUNCTION rlarp.apply_guid(data jsonb)
RETURNS jsonb
LANGUAGE plv8
AS $function$
function findMostRecentPrice(data) {
let mostRecentPrice = null;
let mostRecentYear = null;
// Iterate through each product
data.forEach( data.hist => {
// Check if the product matches the customer channel and version
if (product.chan === cust && (product.v1ds === prod || product.v0ds === prod)) {
// Iterate through the seasons for the product
for (let year in product.season) {
// Convert year to number for comparison
let yearNum = parseInt(year);
// Check if this year is more recent than the current most recent year
if (mostRecentYear === null || yearNum > mostRecentYear) {
mostRecentYear = yearNum;
// Update the most recent price
mostRecentPrice = product.season[year].price_usd;
}
}
}
});
return mostRecentPrice;
}
// Example usage:
const jsonData = data;
const cust = 'W'; // or 'D', depending on the customer
const prod = 'TUH10000'; // the product version you're interested in
const price = findMostRecentPrice(jsonData.data, cust, prod);
console.log(`The most recent price for the customer is: ${price}`);
return price;
$function$;