How to Update the Order-Items While Editing an Order on the WooCommerce Admin Order Screen [closed]

The woocommerce_order_before_calculate_totals hook executes in the Edit Order admin screen when an item is changed or the ‘recalculate’ button is pressed. This allows you to loop through each item and fee in the order and edit as required. I have a fee called ‘Deposit’ which I update if it exists or I add if it doesn’t.

function custom_order_before_calculate_totals($and_taxes, $order ) {
    // The loop to get the order items which are WC_Order_Item_Product objects since WC 3+
    // loop all products and calculate total deposit
    $total_deposit = 0;
    foreach( $order->get_items() as $item_id => $item ) {
        // get the WC_Product object
        $product = $item->get_product();

        // get the quantity
        $product_quantity = $item->get_quantity();

        // get the deposit amount
        $deposit = $product->get_attribute('deposit') * $product_quantity;

        // sum of deposits from all products
        $total_deposit += $deposit;
    }


    // update the Deposit fee if it exists
    $deposit_fee_exists = false;
    foreach( $order->get_fees() as $item_id => $item_fee ) {
        $fee_name = $item_fee->get_name();

        if ( $fee_name == 'Deposit' ) {
            $item_fee->set_tax_status('none'); // no tax on deposit
            $item_fee->set_total($total_deposit);
            $deposit_fee_exists = true;
            break;
        }
    }

    // if there isn't an existing deposit fee then add it
    if ( $total_deposit > 0 && !$deposit_fee_exists ) {
        // Get a new instance of the WC_Order_Item_Fee Object
        $item_fee = new WC_Order_Item_Fee();

        $item_fee->set_name( "Deposit" ); // Generic fee name
        $item_fee->set_amount( $total_deposit ); // Fee amount
        $item_fee->set_tax_status( 'none' ); // or 'none'
        $item_fee->set_total( $total_deposit ); // Fee amount

        // Add Fee item to the order
        $order->add_item( $item_fee );
    }
}
add_action( 'woocommerce_order_before_calculate_totals', "custom_order_before_calculate_totals", 10, 3);