Noobie working with two collections and repeater

I really apologise in advance for this… I’m a complete novice with coding and I’ve been trying to put something together for my site. I’ve got a long way with the project BUT I’m failing at the last hurdle.

I’m trying to check a lost of customers from a collection (criteriacheck) and put their information through different mortgage products which are on another collection (currentRates). Then for each customer I want to display a simple “yes we can” or “no we cant” type message in their repeater box.

I know I can get each element to work individually but when I put it all together I’m hitting a brick wall and I’ve been working on this last part for DAYS AHHHHH!!!H!H!H

This issue seems to be with this part of the code because everything is returning the expected results but this part just returns ‘undefined’

I’d really appreciate some help or a point in the right direction with where I’m going wrong

Many thanks in advance

Mark
CODE BELOW

import wixData from ‘wix-data’ ;

$w . onReady ( function () {
$w ( “#remoCheckRepeater” ). onItemReady ( ( $item , itemData , index ) => {
$item ( “#nameData” ). text = itemData . title ;
$item ( “#balanceData” ). text = itemData . borrowingAmount . toString ();
$item ( “#remoDateData” ). text = itemData . remortgageDate . toLocaleDateString ();
$item ( “#ercData” ). text = itemData . currentErc . toString ();
$item ( ‘#outcomeData’ ). text = itemData . dataTest . toString ();

} )
} )

wixData . query ( “CriteriaCheck” )
. ascending ( “remortgageDate” )
. eq ( “type” , “rate checker” )
. find ()
. then (( results ) => {
//create array with result from search of collection for rate checks
let dataArray = results . items ;
loopResults ( dataArray );
})

async function loopResults ( dataArray ) {

//loop over search results and add to array if we can do current mortgage cheaper.
for ( let i = 0 ; i < dataArray . length ; i ++) {
let remoDate = dataArray [ i ]. remortgageDate ;
let remoBalance = dataArray [ i ]. borrowingAmount ;
let remoRepaymentMethod = dataArray [ i ]. currentRepaymentMethod ;
let remoTerm = dataArray [ i ]. term ;
let remoPaying = dataArray [ i ]. currentPayment ;
let remoErc = dataArray [ i ]. currentErc ;
let remoLtv = dataArray [ i ]. ltvPc ;

//get the difference between today and the remo end date
let date1 = new Date ();
let currentTimeLeft = remoDate . getTime () - date1 . getTime ();
let currentMonthsLeft = Math . round ( currentTimeLeft / 2629746000 );

//execute query on our products to work out the total cost over months left on the deal
let remoTotalCost = await sortTotalCost ( remoLtv , currentMonthsLeft , remoBalance , remoRepaymentMethod , remoTerm )
console . log ( 'this is the loopResults ’ + remoTotalCost )

//work out the cost of the current mortgage over the months left on the deal
let currentTotalCost = remoPaying * currentMonthsLeft ;

//compare the difference in the current total cost vs the remo total cost over the period
let costDifference = currentTotalCost - remoTotalCost ;
//if the amount saved between the two deals is higher than the current erc success
if ( costDifference > remoErc ) {
//we can save you money over your current deal
dataArray [ i ]. dataTest = “yes we can save you money” ;

} else if ( costDifference < remoErc && currentMonthsLeft <= 6 ) {
// the new deal will cost more but you are withing the next product window
dataArray [ i ]. dataTest = “no we cant save you money but you’re within 6 months” ;

} else {
dataArray [ i ]. dataTest = “no we cant save you money” ;
}
}

//add array data to the repeater to display
return $w ( “#remoCheckRepeater” ). data = dataArray ;
}

async function sortTotalCost ( ltv , mthsLeft , balance , method , term ) {
await wixData . query ( “CurrentRates” )
. ge ( “ltv” , ltv )
. ascending ( “ltv” , “fees” )
. find ()
. then (( results ) => {
let items ;

if ( results . items . length  >  0 ) { 
  items  =  results . items ;  //all items in the query 
}  **else**  { 
  console . log ( "NOTHING MATCHES THIS SEARCH" ) 
} 

let remoCost = totalCostLoop ( items , mthsLeft , balance , method , term )
console . log ( 'this is the sortTotalCost ’ + remoCost )
return remoCost ;
})
}

//function to work out which out the all the rates in the collection is the lowest cost overall
function totalCostLoop ( item , mths , bal , mthd , term ) {
let lowestTotalCost = 0 ;
//check if the calculation should be based in C&I or IO
if ( mthd !== “repayment” ) {

//loop over all the products and work out the overall cost of each using IO repayment method 
**for**  ( let  i  =  0 ;  i  <  item . length ;  i ++) { 
  let  monthlyCost  =  0 ; 
  monthlyCost  =  item [ i ]. interestRate  /  100  /  12  *  bal ;  
  let  totalCost  =  monthlyCost  *  mths  +  item [ i ]. fees  -  item [ i ]. cashBack ; 
  
  //capture which is the lowest cost deal 
  if  ( i  ===  0 ) { 
  lowestTotalCost  =  totalCost ; 
  }  **else if**  ( i  >  0  &&  totalCost  <  lowestTotalCost ){ 
  lowestTotalCost  =  totalCost ; 
  }       
} 

} else {
for ( let i = 0 ; i < item . length ; i ++) {
let monthlyCost = 0 ;
let monthlyRate = item [ i ]. interestRate / 100 / 12 ;
//calculate the monthly cost of the mortgage using C&I repayment method
monthlyCost = ( bal * monthlyRate * ( Math . pow ( 1 + monthlyRate , ( term * 12 ))) / ( Math . pow ( 1 + monthlyRate , ( term * 12 )) - 1 ));
let totalCost = monthlyCost * mths + item [ i ]. fees - item [ i ]. cashBack ;
//console.log(‘the total monthly cost is £’+monthlyCost+’ and the total cost is £’+totalCost)
if ( i === 0 ) {
lowestTotalCost = totalCost ;
} else if ( i > 0 && totalCost < lowestTotalCost ){
lowestTotalCost = totalCost ;
}
}
}
console . log ( 'this is the totalCostLoop ’ + lowestTotalCost )
return lowestTotalCost ;
}

Try this one and also use some more CONSOLE-LOGS inside your code!

import wixData from 'wix-data';

$w.onReady(function () {
    $w("#remoCheckRepeater").onItemReady(($item, itemData, index)=> {
        $item("#nameData").text = itemData.title;
        $item("#balanceData").text = itemData.borrowingAmount.toString();
        $item("#remoDateData").text = itemData.remortgageDate.toLocaleDateString();
        $item("#ercData").text = itemData.currentErc.toString();
        $item('#outcomeData').text = itemData.dataTest.toString();
    });
    wixData.query("CriteriaCheck")
    .ascending("remortgageDate")
    .eq("type","rate checker")
    .find()
    .then((results)=> {
        let dataArray = results.items;
        loopResults(dataArray);
    });
});

async function loopResults(dataArray) {
    for (let i = 0; i < dataArray.length; i++) {
        let date1 = new Date();
        let remoDate = dataArray[i].remortgageDate;
        let remoBalance = dataArray[i].borrowingAmount;
        let remoRepaymentMethod = dataArray[i].currentRepaymentMethod;
        let remoTerm = dataArray[i].term;
        let remoPaying = dataArray[i].currentPayment;
        let remoErc = dataArray[i].currentErc;
        let remoLtv = dataArray[i].ltvPc;
        //-------------------------------------------
        let currentTimeLeft = remoDate.getTime() - date1.getTime();
        let currentMonthsLeft = Math.round(currentTimeLeft / 2629746000);
        //-----------------------------------------------
        let remoTotalCost = await sortTotalCost(remoLtv, currentMonthsLeft, remoBalance, remoRepaymentMethod, remoTerm); console.log('this is the loopResults '+ remoTotalCost);
        let currentTotalCost = remoPaying * currentMonthsLeft;    
        let costDifference = currentTotalCost - remoTotalCost;
        
        if (costDifference > remoErc) {ataArray[i].dataTest = "yes we can save you money";}
        else if (costDifference < remoErc && currentMonthsLeft <= 6) {
            dataArray[i].dataTest ="no we cant save you money but you're within 6 months";
        }
        else {dataArray[i].dataTest = "no we cant save you money";}

        if(i === dataArray.length-1) {console.log('this is the totalCostLoop '+ lowestTotalCost);
            return $w("#remoCheckRepeater").data = dataArray;
        }
    }
} 

async function sortTotalCost(ltv, mthsLeft, balance, method, term) {
    return wixData.query("CurrentRates")
    .ge("ltv", ltv)
    .ascending("ltv", "fees")
    .find()
    .then(async(results) => {
        let items; 
        if(results.items.length > 0) {
            items = results.items; console.log("Found ITEMS: ", items)
        } else {console.log("NOTHING MATCHES THIS SEARCH");}
        let remoCost = await totalCostLoop(items, mthsLeft, balance, method, term); console.log('this is the sortTotalCost '+ remoCost)
        return remoCost;
    });
}
    
function totalCostLoop(item, mths, bal, mthd, term) {
    let lowestTotalCost=0;
    if (mthd !== "repayment") {
        for (let i = 0; i < item.length; i++) {
            let monthlyCost = 0;
            monthlyCost = item[i].interestRate / 100 / 12 * bal; 
            let totalCost = monthlyCost * mths + item[i].fees - item[i].cashBack;
            if (i === 0) {lowestTotalCost = totalCost;} 
            else if (i > 0 && totalCost < lowestTotalCost){lowestTotalCost = totalCost;}   
            if(i === item.length-1) {console.log('this is the totalCostLoop '+ lowestTotalCost);
                return lowestTotalCost;
            }   
        }
    } else {
        for (let i = 0; i < item.length; i++) {
            let monthlyCost = 0;
            let monthlyRate = item[i].interestRate / 100 / 12;
            monthlyCost = (bal * monthlyRate * (Math.pow(1 + monthlyRate, (term*12))) / (Math.pow(1 + monthlyRate, (term*12)) - 1));
            let totalCost =  monthlyCost * mths + item[i].fees - item[i].cashBack;
            if (i === 0) {lowestTotalCost = totalCost;}
            else if (i > 0 && totalCost < lowestTotalCost){lowestTotalCost = totalCost;}      
            if(i === item.length-1) {console.log('this is the totalCostLoop '+ lowestTotalCost);
                return lowestTotalCost;
            }
        }
    }    
}

Also use CODE-BLOCKS to present your code inside your post → like i do!
Also try to pay more attention onto the formating of your code-syntax.
Alsways try to write your code clearly, as short as possible giving it a good overview.

hey velo-ninja;

Thanks for wading through that and giving me the pointers (told you I was a noob)

I’ve gone away and looking up some basics around promises and I’ve cracked it.

I do take the point about tiding it all up and commenting on it better.

Anyway here is the working code.

import wixData from 'wix-data';

$w.onReady(function () {
  
  $w("#myRepeater").onItemReady( ($item, itemData, index) => {
    $item("#nameData").text = itemData.title;
    $item("#balanceData").text = itemData.borrowingAmount.toString();
    $item("#remoDateData").text = itemData.remortgageDate.toLocaleDateString();
    $item("#ercData").text = itemData.currentErc.toString();
    $item('#outcomeData').text = itemData.newData.toString();
 
  } )
} )


function getCustomer(){
  return new Promise((resolve, reject) => {
    wixData.query("collection1")
    .ascending("remortgageDate")
    .eq("type","rate checker")
    .find()
    .then((results) => {
    //create array with result from search of collection for rate checks      
    const finalData = results.items;
    resolve(finalData)
  });
  })
}
    

function getRates(ltv) {
  return new Promise((resolve, reject) => {
  let items; 
  wixData.query("collection2")
   .ge("ltv", ltv)
   .ascending("ltv", "fees")
   .find()
    .then((results) => {
    if(results.items.length > 0) {
      items = results.items; //all items in the query
    } else {
      console.log("NOTHING MATCHES THIS SEARCH")
    }
    resolve(items);
    });
  });
}

let array = [];
getCustomer()
.then(customers => {
 let count = customers.length
 let pass = 0;
  customers.forEach(customer => {
    getRates(customer.ltvPc)
      .then(rates => {
      let date1 = new Date();
      let currentTimeLeft = customer.remortgageDate.getTime() - date1.getTime();
      let currentMonthsLeft = Math.round(currentTimeLeft / 2629746000);
      const lowestPrice = Math.round(totalCostLoop(rates, currentMonthsLeft, customer.borrowingAmount, customer.currentRepaymentMethod, customer.term));
      passResult(customer.currentPayment, currentMonthsLeft, lowestPrice, customer.currentErc)
        .then(outcome => {
        customer.newData = outcome;
        array.push(customer)
        pass += 1;
        if (pass === count) {
         $w("#remoCheckRepeater").data = array;
        }
       })
      })
  });
})


 //function to work out which out the all the rates in the collection is the lowest cost overall
function totalCostLoop(item, mths, bal, mthd, term) {
 let lowestTotalCost=0;
 //check if the calculation should be based in C&I or IO
 if (mthd !== "repayment") {
   //loop over all the products and work out the overall cost of each using IO repayment method
   for (let i = 0; i < item.length; i++) {
    let monthlyCost = 0;
    monthlyCost = item[i].interestRate / 100 / 12 * bal; 
    let totalCost = monthlyCost * mths + item[i].fees - item[i].cashBack;
      
    //capture which is the lowest cost deal
    if (i === 0) {
      lowestTotalCost = totalCost;
    } else if (i > 0 && totalCost < lowestTotalCost){
      lowestTotalCost = totalCost;
    }      
    }
  } else {
    for (let i = 0; i < item.length; i++) {
     let monthlyCost = 0;
     let monthlyRate = item[i].interestRate / 100 / 12;
     //calculate the monthly cost of the mortgage using C&I repayment method
     monthlyCost = (bal * monthlyRate * (Math.pow(1 + monthlyRate, (term*12))) / (Math.pow(1 + monthlyRate, (term*12)) - 1));
     let totalCost =  monthlyCost * mths + item[i].fees - item[i].cashBack;
     //console.log('the total monthly cost is £'+monthlyCost+' and the total cost is £'+totalCost)
     if (i === 0) {
     lowestTotalCost = totalCost;
     } else if (i > 0 && totalCost < lowestTotalCost){
     lowestTotalCost = totalCost;
     }     
    }
  }
return lowestTotalCost;
}


function passResult(currentPayment, monthsLeft, remoCost, erc) {
  
  //work out the cost of the current mortgage over the months left on the deal
  let currentTotalCost = currentPayment * monthsLeft;

  //compare the difference in the current total cost vs the remo total cost over the period
  let costDifference = currentTotalCost - remoCost;
  
  if (costDifference > erc) {
  //we can save you money over your current deal
  return new Promise ((resolve, reject) => 
    resolve("yes we can save you money"));
    
  } else if (costDifference < erc && monthsLeft <= 6) {
  // the new deal will cost more but you are withing the next product window
  return new Promise ((resolve, reject) => 
    resolve("no we cant save you money but you're within 6 months"));
  
  } else {
  return new Promise ((resolve, reject) => 
    resolve("no we cant save you money"));
  }
}


You said WORKING-CODE ? Then i am happy :grin:
Seems like you are a quick learner, even used CODE-BLOCKS this time!

GOOD !!!