add a fincancial balance for each stock taking#1213
Conversation
| %td= truncate stock_taking.note | ||
| - balance = 0 | ||
| - for stock_change in stock_taking.stock_changes | ||
| - balance += stock_change.quantity * stock_change.stock_article.gross_price |
There was a problem hiding this comment.
In general, building sums like this may raise performance issues.
If there are a larger number of stock_changes it might be less resource hungry to do this with a db function. Have you considered using sum?
There was a problem hiding this comment.
yes a db function would be much more effective, I will try to implement it this way. I am not very familiar with this kind of programming and was glad that I could get working it this way on my local foodsoft installation to get the balances for our foodcoop...
There was a problem hiding this comment.
I am not very familiar with this kind of programming
Admittedly what I'm suggesting here is quite complicated as we have to take article versioning into account (Something that your stock_change.stock_article automagically did, but with poor performance), so I looked into it myself - Adapting the StockTakings query in the controller's index action like this should work:
@stock_takings = StockEvent
.select(%(
`#{StockEvent.table_name}`.*,
SUM(
`#{StockChange.table_name}`.`quantity`
* (`#{ArticleVersion.table_name}`.`price` + (`#{ArticleVersion.table_name}`.`deposit`) * ((`#{ArticleVersion.table_name}`.`tax`) + 1))
) AS balance
))
.joins(stock_changes: { stock_article: [:article_versions] })
.joins(ArticleVersion.latest_outer_join_sql("#{Article.table_name}.#{Article.primary_key}"))
.where(later_article_versions: { id: nil })
.group('stock_event_id')
.order('date DESC')
.page(params[:page]).per(@per_page)Then in the view you can use format_currency(stock_taking.balance) and remove the balance variable you introduced.
| @@ -8,11 +8,16 @@ | |||
| %th= t '.date' | |||
| %th= t '.note' | |||
| %th | |||
There was a problem hiding this comment.
Shouldn't there be a table heading for this new 'balance' column? 🤔
| %th= t '.article' | ||
| %th= t '.supplier' | ||
| %th= t '.unit' | ||
| %th |
There was a problem hiding this comment.
Shouldn't there be a table heading for this new 'balance' column? 🤔
This PR adds a financial balance to each stock taking in the overview:

and in the detail view for each taking:

So the financial loss (or surplus) of stock takings can be considered in a financial balance.