etapeta (owner)

Revisions

gist: 226942 Download_button fork
public
Public Clone URL: git://gist.github.com/226942.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class LgsProjectCancellation < ActiveRecord::Base
  
  def self.calculate
    # remove all previous data
    self.delete_all
    done = { :unsigned => 0, :ok => 0 }
 
    last_year = 1.year.ago .. Time.now
    Lgs::LoanGrant.all(:conditions => ['project_code <> ?', 9999], :include => :loan_transactions).select {|lg|
      last_year === lg.closing_date
    }.group_by(&:project_code).each {|pid,loans|
      disbursed = 0.0
      approved = 0.0
      loans.each do |loan|
        if loan.signing_date
          approved += as_sdr(loan.original_loan_amount, loan.currency_denomination, loan.signing_date)
          disbursed += loan.disbursements.collect {|disb|
            as_sdr(disb.amount_in_den, loan.currency_denomination, disb.transaction_date)
          }.sum
        else
          done[:unsigned] +=1
        end
      end
      self.create(:project_id => pid.to_i, :sdr_disbursed_amount => disbursed, :sdr_approved_amount => approved)
      done[:ok] += 1
    }
    done
  end
  
  # utility method: converts an amount into SDR
  def self.as_sdr(amount, currency, reference_date)
    if currency == 'SDR'
      amount
    else
      currency_date = Lgs::ExchangeRate.maximum(:begin_date,
        :conditions => ['currency_code = ? and begin_date < ?', currency, reference_date])
      raise "No exchange available for currency #{currency} at #{reference_date}" unless currency_date
      ex = Lgs::ExchangeRate.find(:first, :conditions => {:currency_code => currency, :begin_date => currency_date })
      amount * ex.sdr_rate
    end
  end
  
end