Code Review Friday: (Let's Improve your code, ask Corvid Master)

June 12th, 2020
Join this week code review organized by Corvid master,
Comment your code below(as per instruction) we will analyze provide you suggestion or refactored code that will be easy to read, to modify, and plenty of good practice.

We also welcome experience corvid forum members to share the knowledge and expertise.

Instructions:

*1: FULL PAGE CODE is recommended
*2: Include database structure like Collection name & Field type (if you refer them in the code)
3: Is this a live site? If so, drop a link so, we can check the code.
4: Videos or Images for explanation of what the code does is useful!
Marked * are required

Don’ts

1: Do NOT include any sensitive code (like passwords, secrect key).

// try to rewrite it as xxx if it's used inside the code
const key = "XXX-XXX";

2: Asking any questions unrelated to code review or corvid
3: Screenshot the code and not pasting the code in text format
4: Code that was not working before and asking to fix (Please create a new post in the community, This Post is dedicated to improve your current working code)

Comment not related to refactor for the code will be get deleted to organize

Notes

  • We do code review every friday PST timezone!

  • This post will be locked after 24 hours

Hello again :grin:,

i have generated a code which makes possible the multiple search of several DropDrowns connected to one database.

CODE:

import wixData from 'wix-data';

//-------------- USER-INTERFACE ---------------------
var DATABASE  = "database1"
var DATASET   = "#dataset1"
var REFERENCE1  = "item1" 
var REFERENCE2  = "item2" 
var REFERENCE3  = "item3" 
var REFERENCE4  = "item4" 
var REFERENCE5  = "itemX" 
var REFERENCE6  = "item5" 
//-------------- USER-INTERFACE ---------------------

$w.onReady(function () {});
export function DD1_change(event) {SEARCH_ENGINE()}
export function DD2_change(event) {SEARCH_ENGINE()}
export function DD3_change(event) {SEARCH_ENGINE()}
export function DD4_change(event) {SEARCH_ENGINE()}
export function DD5_change(event) {SEARCH_ENGINE()}
export function DD6_change(event) {SEARCH_ENGINE()}
export function input1_change(event) {SEARCH_ENGINE()}
export function input2_change(event) {SEARCH_ENGINE()}
export function BTNsearch_click(event) {SEARCH_ENGINE()}



function SEARCH_ENGINE() {console.log("Search-Engine started!")
 let input1 = $w("#input1").value
 let input2 = $w("#input2").value
 let item1, item2, item3, item4, item5, item6, item7
 let column1, column2, column3, column4, column5, column6, column7
 let CODE = ""

    console.log()
  console.log(input1)
    console.log(input2)

 if ($w('#DD1').value!=0)  {column1 = REFERENCE1,  item1 = $w('#DD1').value,   CODE=CODE + "1"} else{CODE=CODE + "0"}
 if ($w('#DD2').value!=0)  {column2 = REFERENCE2,  item2 = $w('#DD2').value,   CODE=CODE + "1"} else{CODE=CODE + "0"}
 if ($w('#DD3').value!=0)  {column3 = REFERENCE3,  item3 = $w('#DD3').value,   CODE=CODE + "1"} else{CODE=CODE + "0"}
 if ($w('#DD4').value!=0)  {column4 = REFERENCE4,  item4 = $w('#DD4').value,   CODE=CODE + "1"} else{CODE=CODE + "0"}
 //----------------------------------------------------------------------------------------------------------------------------
 if ($w('#DD5').value!=0)  {column5 = REFERENCE5,  item5 = $w('#DD5').value,   CODE=CODE + "1"} else{CODE=CODE + "0"}
 if (input1!=0 && input2!=0) {column6 = REFERENCE6,  console.log("special"),   CODE=CODE + "1"} else{CODE=CODE + "0"}

 //ABFRAGE----------------------------------------------CODE-ZERO

 console.log(CODE)

 if (CODE=="000000"){$w(DATASET).setFilter(wixData.filter(), console.log("RESET"))} // --------> Baustelle <----------

 //ABFRAGE----------------------------------------------Einzeln
 if (CODE=="100000"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1));}
 if (CODE=="010000"){$w(DATASET).setFilter(wixData.filter().eq(column2, item2));}
 if (CODE=="001000"){$w(DATASET).setFilter(wixData.filter().eq(column3, item3));}
 if (CODE=="000100"){$w(DATASET).setFilter(wixData.filter().eq(column4, item4));}
 if (CODE=="000010"){$w(DATASET).setFilter(wixData.filter().eq(column5, item5));}
 if (CODE=="000001"){$w(DATASET).setFilter(wixData.filter().between(column6, input1, input2));}
 
 //ABFRAGE----------------------------------------------Duo
 if (CODE=="110000"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column2, item2));}
 if (CODE=="011000"){$w(DATASET).setFilter(wixData.filter().eq(column2, item2).eq(column3, item3));}
 if (CODE=="001100"){$w(DATASET).setFilter(wixData.filter().eq(column3, item3).eq(column4, item4));}
 if (CODE=="000110"){$w(DATASET).setFilter(wixData.filter().eq(column4, item4).eq(column5, item5));}
 if (CODE=="000011"){$w(DATASET).setFilter(wixData.filter().eq(column5, item5).between(column6, input1, input2));}
 if (CODE=="101000"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column3, item3));}
 if (CODE=="100100"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column4, item4));}
 if (CODE=="100010"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column5, item5));}
 if (CODE=="100001"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).between(column6, input1, input2));}
 if (CODE=="010001"){$w(DATASET).setFilter(wixData.filter().eq(column2, item2).between(column6, input1, input2));}
 if (CODE=="001001"){$w(DATASET).setFilter(wixData.filter().eq(column3, item3).between(column6, input1, input2));}
 if (CODE=="000101"){$w(DATASET).setFilter(wixData.filter().eq(column4, item4).between(column6, input1, input2));}
 if (CODE=="010010"){$w(DATASET).setFilter(wixData.filter().eq(column2, item2).eq(column5, item5));}
 if (CODE=="001010"){$w(DATASET).setFilter(wixData.filter().eq(column3, item3).eq(column5, item5));}
 if (CODE=="010100"){$w(DATASET).setFilter(wixData.filter().eq(column2, item2).eq(column4, item4));}

 //ABFRAGE----------------------------------------------Trio
 if (CODE=="111000"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column2, item2).eq(column3, item3));}
 if (CODE=="110100"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column2, item2).eq(column4, item4));}
 if (CODE=="110010"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column2, item2).eq(column5, item5));}
 if (CODE=="110001"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column2, item2).between(column6, input1, input2));}
 if (CODE=="101001"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column3, item3).between(column6, input1, input2));}
 if (CODE=="100101"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column4, item4).between(column6, input1, input2));}
 if (CODE=="100011"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column5, item5).between(column6, input1, input2));}
 if (CODE=="010011"){$w(DATASET).setFilter(wixData.filter().eq(column2, item2).eq(column5, item5).between(column6, input1, input2));}
 if (CODE=="001011"){$w(DATASET).setFilter(wixData.filter().eq(column3, item3).eq(column5, item5).between(column6, input1, input2));}
 if (CODE=="000111"){$w(DATASET).setFilter(wixData.filter().eq(column4, item4).eq(column5, item5).between(column6, input1, input2));}
 if (CODE=="001110"){$w(DATASET).setFilter(wixData.filter().eq(column3, item3).eq(column4, item4).eq(column5, item5));}
 if (CODE=="011100"){$w(DATASET).setFilter(wixData.filter().eq(column2, item2).eq(column3, item3).eq(column4, item4));}
 if (CODE=="101100"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column3, item3).eq(column4, item4));}
 if (CODE=="101010"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column3, item3).eq(column5, item5));}
 
 //ABFRAGE----------------------------------------------Quadro
 if (CODE=="111100"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column2, item2).eq(column3, item3).eq(column4, item4));}
 if (CODE=="111010"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column2, item2).eq(column3, item3).eq(column5, item5));}
 if (CODE=="111001"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column2, item2).eq(column3, item3).between(column6, input1, input2));}
 if (CODE=="110101"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column2, item2).eq(column4, item4).between(column6, input1, input2));}
 if (CODE=="110011"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column2, item2).eq(column5, item5).between(column6, input1, input2));}
 if (CODE=="101011"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column3, item3).eq(column5, item5).between(column6, input1, input2));}
 if (CODE=="100111"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column4, item4).eq(column5, item5).between(column6, input1, input2));}
 if (CODE=="010111"){$w(DATASET).setFilter(wixData.filter().eq(column2, item2).eq(column4, item4).eq(column5, item5).between(column6, input1, input2));}
 if (CODE=="001111"){$w(DATASET).setFilter(wixData.filter().eq(column3, item3).eq(column4, item4).eq(column5, item5).between(column6, input1, input2));}
 if (CODE=="011110"){$w(DATASET).setFilter(wixData.filter().eq(column2, item2).eq(column3, item3).eq(column4, item4).eq(column5, item5));}
 
 //ABFRAGE----------------------------------------------X5
 if (CODE=="111110"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column2, item2).eq(column3, item3).eq(column4, item4).eq(column5, item5));}
 if (CODE=="111101"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column2, item2).eq(column3, item3).eq(column4, item4).between(column6, input1, input2));}
 if (CODE=="111011"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column2, item2).eq(column3, item3).eq(column5, item5).between(column6, input1, input2));}
 if (CODE=="110111"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column2, item2).eq(column4, item4).eq(column5, item5).between(column6, input1, input2));}
 if (CODE=="101111"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column3, item3).eq(column4, item4).eq(column5, item5).between(column6, input1, input2));}
 if (CODE=="011111"){$w(DATASET).setFilter(wixData.filter().eq(column2, item2).eq(column3, item3).eq(column4, item4).eq(column5, item5).between(column6, input1, input2));}
/*
  //ABFRAGE----------------------------------------------X6
    if (CODE=="111110"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column2, item2).eq(column3, item3).eq(column4, item4).eq(column5, item5));}
  if (CODE=="111101"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column2, item2).eq(column3, item3).eq(column4, item4).between(column6, input1, input2));}
  if (CODE=="111011"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column2, item2).eq(column3, item3).eq(column5, item5).between(column6, input1, input2));}
  if (CODE=="110111"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column2, item2).eq(column4, item4).eq(column5, item5).between(column6, input1, input2));}
  if (CODE=="101111"){$w(DATASET).setFilter(wixData.filter().eq(column1, item1).eq(column3, item3).eq(column4, item4).eq(column5, item5).between(column6, input1, input2));}
  if (CODE=="011111"){$w(DATASET).setFilter(wixData.filter().eq(column2, item2).eq(column3, item3).eq(column4, item4).eq(column5, item5).between(column6, input1, input2));}
*/
}

My question is, if there isn’t a better solution for such a serch-function?
Because the more DropDowns are integrated insto the project, the much more bigger will be the growing of the code, because of the variants of serch-terms.

Here is a solution, would that work for you?

function SEARCH_ENGINE() {
let filter =  wixData.filter() if ($w('#DD1').value!=0) filter = filter.eq(REFERENCE1,$w('#DD1').value);  if ($w('#DD2').value!=0) filter = filter.eq(REFERENCE2,$w('#DD2').value);  if ($w('#DD3').value!=0) filter = filter.eq(REFERENCE3,$w('#DD3').value);  if ($w('#DD4').value!=0) filter = filter.eq(REFERENCE4,$w('#DD4').value);  if ($w('#DD5').value!=0) filter = filter.eq(REFERENCE5,$w('#DD5').value);   const isSpecial = ""//set condition for special  if (isSpecial) filter = filter.between(column6, $w("#input1").value, $w("#input2").value);   $w(DATASET).setFilter(filter) }

Damn yes it does! :grin: really good!
Have to take some time to study it, THANKS ! ! ! !

To precise my CORVID knowledge, is my train of thought right, when i say…

  1. Creates a new data-filter.
let filter =  wixData.filter() 
  1. This part is the main-part, right?
    Here the “if then query” does the biggest part of job", right?
    Here the resetting of the filter-options takes place right?
    (like —> 1+1 =2) (old filter-options + additional-filter-options = new filter-options)
if ($w('#DD1').value!=0) filter = filter.eq(REFERENCE1,$w('#DD1').value);  if ($w('#DD2').value!=0) filter = filter.eq(REFERENCE2,$w('#DD2').value);  if ($w('#DD3').value!=0) filter = filter.eq(REFERENCE3,$w('#DD3').value);  if ($w('#DD4').value!=0) filter = filter.eq(REFERENCE4,$w('#DD4').value);  if ($w('#DD5').value!=0) filter = filter.eq(REFERENCE5,$w('#DD5').value); 
  1. And here the end-setting of the filter.
$w(DATASET).setFilter(filter)

Happy Friday!

I have built a site for a hotel group to book rooms across multiple properties. I’ve achieved the check-out/booking processing using the WIX-PAY API.

Everything is working as expected, but I feel there are possibly a few improvements that I could make. Specifically:

  1. Ensuring the security of the transaction related to passing the number of nights and rooms (e.g., quantity) from the client to the backend. I posted a question about this here .

  2. Recording the transaction after payment is made . Currently, I’m doing this after the startPayment() function returns, but I’m not confident this is the best approach. For example, I noticed if I use the native Thank You page, this function is technically not returned until the user closes the payment window, and if the user leaves it open, then my recording of the transaction would not trigger (which would be the worst-case possible). I also need to add in triggering emails after the recording so I have the same concerns there too.

Note, the entire payment flow is not working on the live site. I’m assuming this is because I haven’t upgraded the site (yet - will do that when it’s closer to being done). This does work as expected in the editor.

Live site (to this specific page)

CLIENT SIDE CODE:

$w("#dbProperties").onReady(() => {
 //Get current property's ID
 let property = $w("#dbProperties").getCurrentItem();

 // Step 2 - Call backend function passing the current property's ID and cusomer's details 
 // (Next, see steps 3 & 4 in the backend code below.)
createMyPayment(property._id, { firstName, lastName, phone, email, countryCode }, CheckIn, CheckOut, numRooms)

// When the payment has been created and a paymentId has been returned:
     .then((payment) => {
 
 // Step 5 - Call the startPayment() function with the paymentId.
     wixPay.startPayment(payment.id, {     
     "showThankYouPage": false ,"skipUserInfoPage": 
     false })

 // Step 6 - Visitor enters the payment information.
 // When the payment form is completed:
         .then((paymentResult) => {

 // Step 7 - Handle the payment result.
 // (Next, see step 8 in the backend code below.)
         if (paymentResult.status ===  
                "Successful") {
      
      //TBD: Sucess/Confirmation Screen

      //Record transaction/reservation
      let toInsert = {
      "guestFirstName": firstName,
      "guestLastName": lastName,
      "guestEmail": email,
      "guestPhone": Number(phone),
      "guestAddress1": address1,
      "guestAddress2": address2,
      "guestCity": city,
      "guestState": state,
      "guestZip": zip,
      "guestCountry": countryCode,
      "guest1FirstName": guest1FirstName,
      "guest1LastName": guest1LastName,
      "guest2FirstName": guest2FirstName,
      "guest2LastName": guest2LastName,
      "guest3FirstName": guest3FirstName,
      "guest3LastName": guest3LastName,
      "guest4FirstName": guest4FirstName,
      "guest4LastName": guest4LastName,
      "propertyId": property._id,
      "checkIn": CheckIn,
      "checkOut": CheckOut,
      "nights": nights,
      "rooms": numRooms,
      "roomCharges": roomCharges,
      "taxCharges": taxCharges,
      "stayTotal": stayTotal,
      "transactionId": paymentResult.transactionId,
      "payment": paymentResult,
      "property": property
                        };
      wixData.insert("Reservations", toInsert)
           .then((results) => {
                let item = results; 
           })
                .catch((err) => {
                     let errorMsg = err;
                });
 
     //To-Do: Trigger Emails

     } else if (paymentResult.status === "Pending") {
      //TBD: Pending Scenario
     }
  });
  });
})

BACKEND CODE:

export async function createMyPayment(propertyId, userInfo, CheckIn, CheckOut, numRooms) {
 // Step 3 - Create payment info object.
 //Retrive product details from the database
 let property = await wixData.get('Properties', propertyId);
 //Calculate the number of nights (client side function)
 let nights = date_diff_indays(CheckIn, CheckOut);

//Cacluate the rate totals (backend function)
 let rateTotals = await calRate(nights, numRooms, property.dailyRate, property.weeklyRate, property.monthlyRate, property.taxDaily, property.taxWeeklyRate, property.taxMonthlyRate, property.taxRate);

//Set Payment Info
 let paymentInfo = {
      "items": [{
           //Room Line Item
           name: property.title + " (" + numRooms + " 
           Rooms for " + nights + " night(s))",
           price: rateTotals.roomTotal
                },
                { //Tax Line Item
                name: "Tax",
                price: rateTotals.taxTotal
                }
            ],
        amount: rateTotals.grandTotal, 
        userInfo //Customer details
  };

 // Step 4 - Call createPayment() with the payment information and return the paymentId.
 return wixPay.createPayment(paymentInfo);

 // (Next, see step 5 in the client-side.)       
}

I love learning, so let me know where I can improve. If there is anything else that would make reviewing this easier, let me know.

TIA!

Yes the logic is incremental, you add new constraints on top of the previous one adding more and more condition

If no condition set the filter to the empty filter which count as empty and reset the data

The Wix Payment flow is little wierd
But team is aware and improving the flow

For now, better way is to send the data the database
and than use onPaymentUpdate()
onPaymentUpdate - Velo API Reference - Wix.com

to get the reservation ID and update the status and the payment transaction
In this way, the data won’t be removed, when the user refresh the page
and set the update Option to admin Only if possible
So, only you can update the content

The Flow is like this

We create the Payment will all the detail

Store all the value in the database
and get the PAYMENT id from the backend

After the User complete the transaction

the backend function onPaymentUpdate will be trigger and you can
Update the data saved

on the onPaymentUpdate function
You can also see if the status is success if yes you can send the email from there


$w("#dbProperties").onReady(async () => {
 //Get current property's ID
 let property = $w("#dbProperties").getCurrentItem();

 // Step 2 - Call backend function passing the current property's ID and cusomer's details 
 // (Next, see steps 3 & 4 in the backend code below.)
 let paymentID = await getPaymentID();
 // When the payment has been created and a paymentId has been returned:

 let payOptions = {
 "showThankYouPage": false,
 "skipUserInfoPage": false
  }
 // Step 5 - Call the startPayment() function with the paymentId.
 let paymentResult = await wixPay.startPayment(paymentID, payOptions);

 // Step 6 - Visitor enters the payment information.
 // When the payment form is completed:

 // Step 7 - Handle the payment result.
 // (Next, see step 8 in the backend code below.)
 // just show the lightbox of success and failer
 // handle data insertion from the backend event.
 if (paymentResult.status === "Successful") {
 //TBD: Sucess/Confirmation Screen
 //To-Do: Trigger Emails

  } else if (paymentResult.status === "Pending") {
 //TBD: Pending Scenario
  }
})

let lastPaymentId = "", lastPaymentOpt;
async function getPaymentID() {
 

 let paymentOptions = {
 propertyId: property._id,
 userInfo: { firstName, lastName, phone, email, countryCode },
 CheckIn,
 CheckOut,
 numRooms
  }


 if(lastPaymentId) {
 if(JSON.stringify(paymentOptions) === JSON.stringify(lastPaymentOpt) ) {
 return lastPaymentId;
    }
  }
 // insert all the value to the database
 let inserted = await insertToDatabase();
 paymentOptions.reservationID = inserted._id;
 // and than use the backend to update the status
 let payment = await createMyPayment(paymentOptions)
 lastPaymentId = payment.id;
 lastPaymentOpt = paymentOptions;
}


async function insertToDatabase() {
 try {

 //Record transaction/reservation
 let toInsert = {
 "guestFirstName": firstName,
 "guestLastName": lastName,
 "guestEmail": email,
 "guestPhone": Number(phone),
 "guestAddress1": address1,
 "guestAddress2": address2,
 "guestCity": city,
 "guestState": state,
 "guestZip": zip,
 "guestCountry": countryCode,
 "guest1FirstName": guest1FirstName,
 "guest1LastName": guest1LastName,
 "guest2FirstName": guest2FirstName,
 "guest2LastName": guest2LastName,
 "guest3FirstName": guest3FirstName,
 "guest3LastName": guest3LastName,
 "guest4FirstName": guest4FirstName,
 "guest4LastName": guest4LastName,
 "propertyId": property._id,
 "checkIn": CheckIn,
 "checkOut": CheckOut,
 "nights": nights,
 "rooms": numRooms,
 "roomCharges": roomCharges,
 "taxCharges": taxCharges,
 "stayTotal": stayTotal,
 "transactionId": paymentResult.transactionId,
 "payment": paymentResult,
 "property": property,
    };

 let results = await wixData.insert("Reservations", toInsert)
 return results;
  }
 catch(e) {
 console.log("Error: Failed to insert to database : " e.message );
  }
}


// backend/events.js
export async function wixPay_onPaymentUpdate(event) {
 let paymentId = event.payment.id;
 let newTransactionStatus = event.status;


 let name = event.payment.items[0].name;  //`${property.title} (${numRooms} Rooms for ${nights} night(s)) | ${reservationID}`
 const reservationID = name.split("|").trim();

 console.log({reservationID, name});


 let reservation = await wixData.get("Reservations", reservationID)
 reservation.status = newTransactionStatus;
 reservation.paymentId = paymentId;

}

export async function createMyPayment({propertyId, userInfo, CheckIn, CheckOut, numRooms, reservationID}) {
 // Step 3 - Create payment info object.
 //Retrive product details from the database
 let property = await wixData.get('Properties', propertyId);
 //Calculate the number of nights (client side function)
 let nights = date_diff_indays(CheckIn, CheckOut);

 //Cacluate the rate totals (backend function)
 let rateTotals = await calRate(nights, numRooms, property.dailyRate, property.weeklyRate, property.monthlyRate, property.taxDaily, property.taxWeeklyRate, property.taxMonthlyRate, property.taxRate);

 //Set Payment Info
 let paymentInfo = {
 "items": [
      {
 //Room Line Item
 name: `${property.title} (${numRooms} Rooms for ${nights} night(s)) | ${reservationID}`,
 price: rateTotals.roomTotal
      },
      { //Tax Line Item
 name: "Tax",
 price: rateTotals.taxTotal
      }
    ],
 amount: rateTotals.grandTotal,
 userInfo //Customer details
  };

 // Step 4 - Call createPayment() with the payment information and return the paymentId.
 return wixPay.createPayment(paymentInfo);

 // (Next, see step 5 in the client-side.)       
}

This is code is not tested just to show you the flow of the site

I need help with building out a custom blog post page. The biggest issue right now is that it works in preview, but NOT when I publish the site, so I’m not sure what I’m doing wrong.

Here is my post extra data collection. As you can see, its referencing the blog post collection.


here is my page code:

import wixData from 'wix-data';

let currentPost
$w.onReady(function () {

    $w("#post1").getPost().then(async post => {
        currentPost = await loadExtraPostData(post)
        assignPostDataToUIElements()
    });
})

async function loadExtraPostData(post) {

 let postDataFromCollection = await wixData.query("PostExtraData")
        .eq("post", post._id)
        .find()

    postDataFromCollection = postDataFromCollection.items[0]
 return mergePostData(post, postDataFromCollection)
}

async function mergePostData(post, extraData) {
 return Object.assign({}, post, extraData)
}

function assignPostDataToUIElements() {
    $w("#postTitle").text = currentPost.postTitle
    $w("#authorName").text = `Written by: ${currentPost.authorName}`
    $w("#columnStrip1").background.src = currentPost.coverImage
    $w("#columnStrip1").show("fade")
}

Here is my ‘backend code’ Although I’m not sure if I put this in the right spot:

import wixData from 'wix-data';

export async function PostReactionData_beforeInsert(item, context) {

 const { items } = await wixData.query("PostReactionData")
        .eq("userId", item.userId)
        .eq("post", item.post)
        .find()
 if (items.length) {
 return Promise.reject("Duplicated Likes Forbidden")
    }
 return item
}

This is located in backend–>data.jsw

This is the example i was following: https://www.wix.com/corvid/example/custom-post-page

Any help would be super appreciated! My site is supposed to go live today, and I thought I was good to go because it was working in preview.

Thank you @salman-hammed . I had figured this was part of the solution.

A couple of follow up questions:

  1. Can you explain the logic in getPaymentID () function. Specifically around lastPaymentId ?

  2. Do I understand the flow correctly:

  3. User completes form and selects submit

  4. Insert form data into Reservation collection

  5. Call backend function createMyPayment passing the payment options (property ID & userInfo, newly inserted Reservation id)

  6. In backend function, query the Property collection details based on the passed property ID, and query the Reservation collection based on the passed reservation id.

  7. This will give me the property being reserved AND the details from the form (i.e., the nights, check-in/out dates, etc.)

  8. Return to client with the Payment ID

  9. Call backend function startPayment passing the Payment ID & payOptions.

  10. Return to client and handle results

  11. Then using the backend event function wixPay_onPaymentUpdate to update the previously inserted Reservation record with the completed/updated Payment details.

Or did I totally misunderstand?

Thank you again!

Hey Juwairia
Im not spotting anything in your code that should result in flaws at first glance (which is why i think my advice on the other post you made was something might not be in a live database), based on that thread (which i would have wish you had referenced here so people can see its the same issue) i have seen the “preview works, publish does not” before when something have to be in the backend but wix forgets to mention it.
In your case i would try moving the “getpost” to backend code since its a “recieve all information” It would not surprise me if this is the case that on the published version it rejects the request.

Hi, thanks for your response.
If I paste this code (below) into the backend, it won’t work because its referencing #post1 so its saying the code is unreachable. Thoughts on how I can include it?

Sorry for late reply that is exactly what i meant

the reason is, sometimes the user close the payment and open again
so, this will just prevent it to reduce the dublication
remember we are now storing the data in the database
so we check if all the form value is same
If it’s same, we are just gonna give the lastPaymentId
that was generated instead of creating one everytime

No worries at all. Really truly appreciate all the help!
Im still not 100% clear on the lastPaymentId logic. I get the concept you described but when I run through the logic you shared it will always be empty. I can’t find a secenario where it would be rerun and would be populated, but to be honest that’s the least of my concerns.

Aside from that, I’m fuzzy on how exactly wixPay_onPaymentUpdate ( event ) works. I’ve read the documentation and the way I understand it is, after the payment is executed IF there is an update to the payment status (e.g., Pending to Successful…) then it executes. If that’s correct and it only executes on an updated status then I don’t see where to put the logic to update the Reservation recorded with the payment details (I want to insert the payment object into the collection with the reservation record) and to trigger the various emails? I need to do those two things on a successful payment. If the payment is successful from the beginning (at the time of submit) will the Payment Update event fire?

I updated my code according to what you shared. Works like a champ in the editor (aside from the Payment Update event which per documentation won’t fire in preview mode). However when I run it live it falls apart when calling the backend code (throws an error about the callback and I narrowed it down to the first call of the backend code). My site isn’t upgraded yet, is backend code a premium feature?

Again, your help is much appreciated.

Yes, it’s a requires to be tested in lives site
for now set the payment to 1 dollar and do the live test

and you can just create a test function
and call the function from the frontend to test the email
that’s how i test it

Closing the thread
hope this was useful,
We(Corvid master) will do Code review on every Friday ,
get ready for the next code review on 19th June
Happy coding :v: