Module: NubeFact::Sunat

Extended by:
Sunat
Included in:
Sunat
Defined in:
lib/util/sunat.rb

Overview

WARNING WIP

This is a very basic implementation to obtain sunat dollar exchange rate. I wrote it really quick. Please don’t rely on it. It currently uses two providers. there is no guarantee that the will work, or the response format will change.

WARNING WIP

Defined Under Namespace

Classes: InvalidDate

Instance Method Summary collapse

Instance Method Details

#dollar_from_preciodolarObject



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/util/sunat.rb', line 73

def dollar_from_preciodolar
  url = URI("https://api.preciodolar.com/api/history/?time_interval=day&country=pe&bank_id=13&source=bank")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true

  request = Net::HTTP::Get.new(url)
  request["Content-Type"] = 'application/json'
  request["cache-control"] = 'no-cache'
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  response = http.request request
  result = JSON.parse(response.read_body)

  result.last["sell"]
end

#dollar_from_sunat(date = Date.today) ⇒ Object

Raises:



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/util/sunat.rb', line 27

def dollar_from_sunat(date = Date.today)
  raise InvalidDate if date.year < 2000 || date.year > Time.now.year

  doc = Nokogiri::HTML(open("http://www.sunat.gob.pe/cl-at-ittipcam/tcS01Alias?mes=#{date.month}&anho=#{date.year}")) do |config|
    config.noblanks
  end

  result = {}
  day = nil
  doc.css('td.H3, td.tne10').each do |td|
    if day
      result[day] << td.text.strip
      day = nil if result[day].count == 2
    else
      day = td.at(:strong).text.strip.to_i
      result[day] = []
    end
  end

  # result is {day: [buy, sell], day: [buy, sell]}

  if result[date.day]
    rate = result[date.day].last # venta
  else
    # try to get the nearest day.
    i = 0
    while i < date.day
      if result[i]
         rate = result[i].last
      end
      i += 1
    end

    unless rate
      # not possible to get the previous date, lests why with previous month
      prev_month = date.to_datetime.prev_month
      prev_month = Date.new(prev_month.year, prev_month.month, -1)
      warn "Checking with previous month #{prev_month}"
      rate = dollar_from_sunat(prev_month)
    end
  end

  BigDecimal.new(rate)
end

#dollar_rate(date = Date.today) ⇒ Object



16
17
18
19
20
21
22
23
24
25
# File 'lib/util/sunat.rb', line 16

def dollar_rate(date = Date.today)
  begin
    dollar_from_sunat(date)
  rescue => e
    # only rely on preciodolar for current day
    raise e unless date == Date.today
    
    dollar_from_preciodolar
  end
end