I'm facing a very tricky issue that is related to other issues I could identify but the difference with my issue is such that I judged it relevant to put it in a separate one. Here is the issue I have:
I created a rule that is triggered on the "Before saving a commerce order" this rule is being usually triggered when created a new order and when updating an existing order.
The main action of this rule is to dynamically create a new line item (updating an existing line item) of type "coupon" (from the Commerce coupon module). This action is a custom action that is written in php, receives a couple of arguments (among them the order object) and perform the following:
1. Create/load the coupon line item
2. Add the right price components into the line item (here I erase the previous components and put new ones with updated price)
3. Save the line item
4. Add the line item to the commerce_line_items field (in case it is a newly created line item)
The wrong behavior I encounter is spotted on the order view page, when an update operation is made on the Line Item, by the following:
1. The order total which contains the coupon line item doesn't show the correct price (it always show the "previous" price, i'll explain that later)
2. The order total is computed according to the "previous" line item price
By previous what I actually mean is that the amount alway correspond to the previous save that has been made, that could be illustrated as follows:
A. Create new Line item with amount [Line item value: 100 USD | Line item showed on order view page: 100 USD] -> here no problems
B. Go on edit order page, modify the line item value, save order [Line item value: 150 USD | Line item showed on order view page: 100 USD] -> I know the value is correct by going on the database and checking the value of the total_price attached to the line item (even the components are correct)
C. On the edit order page modify again the Line item value, save order [Line item value: 120 USD | Line item showed on order view page: 150 USD]
and so on..
I concluded that the Order is being saved before the line item's new value is being submitted to the database (or some cache ?) but I can't find a way to force the new value to be taken, I tried to use the function commerce_line_item_rebase_unit_price($line_item) in conjuction with the "cart: true" property on the status the order is on, but this threw a "Nesting level too deep" error on the commerce_cart_order_refresh(). This is not the only problem as the problem persist on the whole order page (view and edit) the only way to solve the problem is either to remove the cart: true property or to erase the Line item (with its reference) in the database...
I would like to find a solution that doesn't require to set the cart: true property as I noticed this has a huge hint on performances (each time an order is viewed it is refreshed and thus saved again..., even when the order is being loaded from a view).