Velo Code to compare Inputfield values with database (Stores/Orders) not running

Hello,

I created a Code to check the Input field values of my customers for the return of my product. Basically, I ask them to Input the OrderNumber and their Email and compare it with the Database values from Stores → Orders.

If the Email and the OrderNumber is correct, then I want the customer to be let to another page after the click of send button. And the Input field values should be saved into another database. Otherwise, they should get an error message.

Unfortunately nothing happens, when I click on send.

This is my Code:

import wixData from 'wix-data';
import wixLocation from 'wix-location';

import wixData from 'wix-data';
import wixLocation from 'wix-location';

$w.onReady(function () {
  // Event handler for the click on the "Send" button
  $w('#sendButton').onClick(() => {
    // Retrieve user inputs
    const orderNumber = $w('#orderNumberInput').value;
    const emailAddress = $w('#emailInput').value;

    // Database query for the order number
    wixData.query('Stores/Orders')
      .eq('number', orderNumber)
      .find()
      .then((results) => {
        if (results.items.length > 0) {
          // Check if the entered email address is in the same row
          const order = results.items[0];
          if (order.buyerInfo === emailAddress) {
            // Email address and order number match

            // Extract the content from the "totals" column
            const orderTotals = order.totals;

            // Save input data to the "Retoure" database
            wixData.insert('Retoure', { orderNumber, emailAddress, totals: orderTotals })
              .then(() => {
                // Open the page "www.zodis.de/retoure-adresse"
                wixLocation.to('http://www.abc.de/retoure-adresse');
              })
              .catch((error) => {
                // Error when saving to the "Retoure" database
                console.error('Error when saving to the "Retoure" database:', error);
              });
          } else {
            // Error: Email address does not belong to the order number
            showErrorMessage('The entered email address does not belong to the specified order number.');
          }
        } else {
          // Error: Order number not found
          showErrorMessage('Order number not found.');
        }
      })
      .catch((error) => {
        // Error in the database query
        console.error('Error in the database query:', error);
      });
  });

  // Function to display an error message on the page
  function showErrorMessage(message) {
    // Display the element on the page (e.g., a text element with the ID "errorMessage")
    $w('#errorMessage').text = message;
    $w('#errorMessage').show();
  }
});

Thanks for the support
BR Albert

This appears to be frontend code. For security purposes databases like Stores/Orders can only be queried from the backend and only read by those with Admin permission.

I’d recommend moving this logic to a Velo Web Module Calling Backend Code from the Frontend and then calling that function from the frontend.

So essentially you can end up on the frontend with something like:

let orderExists = await checkOrder(orderNumber, email);

if (orderExists) { wixLocation.to('http://www.abc.de/retoure-adresse') }

This way the query and insert happens on the backend without rogue users being able to craft their own queries and inserts.

Additionally may want to check the collection permissions on the Retoure database as this doesn’t seem like data that users should be able to change themselves: CMS: Collection Permissions Overview | Help Center | Wix.com

These changes should both make the code secure and get it to work. Hope that helps!

2 Likes

Hi Anthony,

thanks for support. I changed the Code and I got a success message on the preview mode.
However if I try it on the live website i get an error message with the following statement:
Error: Unable to handle the request. Contact the site administrator or view site monitoring logs for more information.

After checking the protocols it basically says that the person missing permissions to perform this action. But I have already set all permissions to “All side Members” in my Retoure Database.

I assume the error is with the Stores/Orders permissions, as they can not be changed.
They are set to Admin only, which makes the Code not work for usual Customers.

They need to have at least read access, so that there input can be compared with the Stores/Orders.

Due to testing with the Admin account (Live and on Preview), I´m confident that the Code works.

Do you have an Idea what I can do to give the customers at least read access?

Btw: The Protocol information looks like this:

If you are intersted in the Code:

Frontend:

import wixLocation from 'wix-location';
import { sendButtonClicked } from 'backend/my-backend';

$w.onReady(function () {
  // Event handler for the click on the "Send" button
  $w('#sendButton').onClick(async () => {
    // Retrieve user inputs
    const orderNumber = $w('#orderNumberInput').value;
    const emailAddress = $w('#emailInput').value;

    try {
      // Call the backend function
      await sendButtonClicked(orderNumber, emailAddress);

      // If the execution reaches this point, it means the backend function succeeded
      // Open the page "http://www.abc.de/retoure-adresse"
      wixLocation.to('http://www.abc.de/retoure-adresse');
    } catch (error) {
      // Display error message on the page
      showErrorMessage(error.message);

      // Log the error in the browser console
      console.error('Error in frontend code:', error);
    }
  });

  // Function to display an error message on the page
  function showErrorMessage(message) {
    // Display the element on the page (e.g., a text element with the ID "errorMessage")
    $w('#errorMessage').text = message;
    $w('#errorMessage').show();
  }
});

Backend:

import wixData from 'wix-data';

export function sendButtonClicked(orderNumber, emailAddress) {
  // Database query for the order number
  return wixData.query('Stores/Orders')
    .eq('number', orderNumber)
    .find()
    .then((results) => {
      if (results.items.length > 0) {
        // Check if the entered email address is in buyerInfo
        const order = results.items[0];
        if (order.buyerInfo && order.buyerInfo.email === emailAddress) {
          // Email address is in buyerInfo

          // Extract content from the "totals" column
          const orderTotals = order.totals;

          // Save user inputs to the "Retoure" database
          return wixData.insert('Retoure', { orderNumber, emailAddress, totals: orderTotals })
            .then((result) => {
              console.log('Insert successful:', result);
            })
            .catch((insertError) => {
              console.error('Error when saving to the "Retoure" database:', insertError);
              throw insertError;
            });
        } else {
          // Error: Email address does not belong to the order number
          throw new Error('The entered email address does not belong to the specified order number.');
        }
      } else {
        // Error: Order number not found
        throw new Error('Order number not found.');
      }
    })
    .catch((error) => {
      console.error('Error in backend code:', error);
      throw error; // rethrow the error to ensure it's logged in Wix monitoring
    });
}

Thanks
BR Albert

You’ll want to do the find() with the suppressAuth option as in: .find({suppressAuth: true})

Works thanks for the hint

1 Like