I created an application that tracks book sales and, hopefully, is going to calculate royalties.
Now I am tracking sales in orders. Each order has_many: line_items. When the new position is saved, I calculate the total sales of this product, so I have the total sales.
Each author has several royalty rules based on their contract. For example, from 0 to 5000 copies are sold, they get 10 percent. 5001 to 10,000, they get 20 percent. First, I calculated the author’s share for each position. It worked well, but then I realized that my application chooses which royalty rule to apply based on total sales. If I place a large order, it is possible that royalties will be calculated with a high royalty rate for the entire position, when in fact the royalties should be calculated on the basis of both a lower and a high royalty rate (as in one line the element pushes the total sales, past the recall point of the royalty rule).
So my question is how best to do this. I studied the use of ranges, but this is all a little new to me, and the code is getting a bit complicated. Here, admittedly, is the clumsy code that I use to pull all the royal rules for a given contract into an array:
def royalty_rate
@product = Product.find_by_id(product_id)
@total_sold = @product.total_sold
@rules = Contract.find_by_product_id(@product).royalties
... where next?
end
@rules has: bottom and top for each royalty rule, so for this product the first: the bottom will be 0 and the top will be 5000, then the second: the bottom will be 5001, and the second: the top will be 10,000, etc.
Any help or ideas with this would be appreciated. This is actually the last step for me to get a fully functional version that I can play with.
I used this code below to select a specific rule based on the value of total_sold, but again, which has the effect of cumulative sales and choosing the highest royalty rate instead of splitting them.
@rules = @contract.royalties.where("lower <= :total_sold AND upper >= :total_sold", {:total_sold => @total_sold}).limit(1)
.