43 lines
1.3 KiB
MySQL
43 lines
1.3 KiB
MySQL
|
CREATE OR REPLACE FUNCTION rlarp.guidancejsd(_p jsonb, cust text, prod text)
|
||
|
RETURNS jsonb
|
||
|
LANGUAGE plv8
|
||
|
AS $function$
|
||
|
|
||
|
|
||
|
function findMostRecentPrice(data, cust, prod) {
|
||
|
let mostRecentPrice = null;
|
||
|
let mostRecentYear = null;
|
||
|
|
||
|
// Iterate through each product
|
||
|
data.forEach(product => {
|
||
|
// 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 = _p;
|
||
|
|
||
|
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$;
|