basic usermanagement and various fixes
[smr.git] / gui / app / models / position.rb
blobe077a1342564547b5dddff685a72a943d99cb2aa
2 # This file is part of SMR.
4 # SMR is free software: you can redistribute it and/or modify it under the
5 # terms of the GNU General Public License as published by the Free Software
6 # Foundation, either version 3 of the License, or (at your option) any later
7 # version.
9 # SMR is distributed in the hope that it will be useful, but WITHOUT ANY
10 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
11 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License along with
14 # SMR.  If not, see <http://www.gnu.org/licenses/>.
16 class Position < ActiveRecord::Base
17     belongs_to :Portfolio, :foreign_key=>'id_portfolio'
18     belongs_to :Stock, :foreign_key=>'id_stock'
19     has_many :PositionRevision, :foreign_key=>'id_position'
21     # define scopes for easier finding
22     scope :closed, -> { where('position.closed>0') }
23     scope :open, -> { where(:closed => false) }
25     # returns Time object from unix-timestamp in closed column
26     def time_closed
27         Time.at(self.closed)
28     end
30     ##
31     # (re)calculate all PositionRevision (s)
32     def process_revisions
33         shares = invested = 0
34         orders = Order.where(:id_position=>self.id).where("quote>0")
36         orders.each do |o|
37             rev = PositionRevision.find_by_id_order(o.id)
39             if o.type == 'sale' then
40                 shares   -= o.shares
41                 invested -= o.shares * o.quote
42             else
43                 shares   += o.shares;
44                 invested += o.shares * o.quote
45             end
46             rev.shares = shares
47             rev.invested = invested
48             rev.save
49         end
50     end
51 end