# Validate Order Unit and Calculate Total Price

In the Order Management App, Back Office users assign **Order Unit** to suppliers.\
The system must validate that the selected unit is valid and must automatically calculate **Total Price** based on the selected unit.

This section explains how to implement **client‑side validation and calculation** using **JavaScript customization** in App Designer.

***

### Requirement

1. **Order Unit validation**
   * Order Unit must be **less than or equal to In Stock**
   * Order Unit must be **less than or equal to Remain Order Unit**
2. **Automatic calculation**
   * Total Price must be calculated automatically when Order Unit changes

***

### Objective

By completing this section, you will learn how to:

* Validate Order Unit input on the UI layer
* Prevent invalid data entry before saving
* Auto‑calculate Total Price dynamically
* Integrate JavaScript customization into App Designer actions

***

### Step 1: Create / Update JavaScript Customization File

From the **ONEWEB workspace**, create or update the following JavaScript file:

```
/MasterWeb/WebContent/manual/js/doc/order/
order_request_item_back_office_update_mode.js
```

Add or override the following functions.

#### JavaScript Validation and Calculation Logic

```
// Auto script when popup is opened
function loadUpdateManyManual() {
    calPriceByInputUnit();
}

// Validate Order Unit and calculate Total Price
function calPriceByInputUnit() {

    $("[name=UNIT_BY_BACK_OFFICE]").change(function () {

        var stock = parseInt($("[name=IN_STOCK]").val());
        var remain = parseInt($("[name=REMAIN_ORDER_UNIT]").val());
        var orderUnit = parseInt($("[name=UNIT_BY_BACK_OFFICE]").val());

        // Validation: Order Unit must not exceed stock or remaining unit
        if (orderUnit > stock || orderUnit > remain) {

            alert('Unit chosen by back office must be less than or equal to stock and remain order unit');
            $("[name=UNIT_BY_BACK_OFFICE]").val('');
            $("[name=UNIT_BY_BACK_OFFICE]").focus();

        } else {
            var pricePerUnit = $("[name=UNIT_PRICE]").val();
            var totalPrice = orderUnit * pricePerUnit;

            console.log('totalPrice: ' + totalPrice);

            $("[name=TOTAL_PRICE]").val(moneyFormat(totalPrice));
        }
    });
}

// Convert number to money format
function moneyFormat(strMoneyA) {

    var strMoney = new String(strMoneyA);

    if (strMoney !== undefined && strMoney !== 'null' && strMoney !== '') {

        strMoney = strMoney.replace(/\,/g, '');
        strMoney = parseFloat(strMoney).toFixed(2);

        var x = strMoney.split('.');
        var x1 = x[0];
        var x2 = x.length > 1 ? '.' + x[1] : '';

        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }

        return x1 + x2;

    } else {
        return '0.00';
    }
}
```

#### What this script does

* Automatically triggers when the **Supplier popup** is opened
* Listens for changes in **Order Unit (UNIT\_BY\_BACK\_OFFICE)**
* Validates Order Unit against **In Stock** and **Remain Order Unit**
* Auto‑calculates **Total Price = Order Unit × Unit Price**
* Formats Total Price in currency format

***

### Step 2: Deploy JavaScript File

1. From the **ONEWEB workspace**, export `EafMasterEar.ear`
2. Deploy the updated EAR file to the server

The JavaScript file:

```
/MasterWeb/WebContent/manual/js/doc/order/order_request_item_back_office_update_mode.js
```

will now be active.

***

### Step 3: Configure Script in App Designer

1. Open **App Designer**
2. Edit entity:

   ```
   Doc Order Request Item - Back Office
   ```
3. From **Tools > Action**, drag **Entity Action** to the area under the entity name
4. Click the **pencil icon** to edit the action

In **Action Field Configuration**:

* **Process Name**: `UPDATE`
* **Script File**:

  ```
  /MasterWeb/manual/js/doc/order/order_request_item_back_office_update_mode.js
  ```
* Click **OK**

***

### Step 4: Save the Entity

Click **Save this Entity** to apply the configuration.

***

### Step 5: Test the Validation and Calculation

1. Log in to **FrontWeb** as a **Back Office user**
2. Go to **To Do List** and claim a job
3. Open **Order Item**
4. Click **Edit Supplier**
5. Change **Order Unit**

#### Expected Result

* If Order Unit exceeds In Stock or Remain Order Unit:
  * Warning message is displayed
  * Input is reset and focus returns to Order Unit field
* If Order Unit is valid:
  * **Total Price** is calculated automatically
  * Value is displayed in currency format

***

### Summary

In this section, you have:

* Implemented client‑side validation for Order Unit
* Prevented invalid supplier allocation at UI level
* Automatically calculated Total Price based on user input
* Integrated JavaScript customization with App Designer

This customization improves **data accuracy, usability, and user experience** for Back Office users and completes the **front‑end validation layer** for supplier allocation in the **Order Management App (Web)**.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.onewebstack.com/tutorials-examples/order-management-app-web/app-designer-customize/validate-order-unit-and-calculate-total-price.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
