module Myfinance

Constants

VERSION

Attributes

account_id[RW]
endpoint[RW]
token[RW]

Public Class Methods

account_id(nome) click to toggle source
# File lib/myfinance/account.rb, line 3
def self.account_id(nome)
  mid = nil
  available_accounts = accounts
  available_accounts.each do | item |
    item = item['account']
    if item['name'] == nome
      mid = item['id']
      break
    end
  end
  mid
rescue => e
  raise "Não foi retornado um array de contas como esperado: #{available_accounts.inspect}. #{e.message}"
end
accounts() click to toggle source
# File lib/myfinance/account.rb, line 18
def self.accounts
  lget '/accounts.json'
end
altera_conta_a_receber(id, entity_id, faturamento) click to toggle source
# File lib/myfinance/conta_a_receber.rb, line 20
def self.altera_conta_a_receber(id, entity_id, faturamento)
  lput "/entities/#{entity_id}/receivable_accounts/#{id}.json", faturamento
end
anexa_arquivo(entity_id, receivable_id, titulo, arquivo) click to toggle source
# File lib/myfinance/anexo.rb, line 18
def self.anexa_arquivo(entity_id, receivable_id, titulo, arquivo)
  post_data = { attachment: {
      attachment: arquivo,
      title: titulo,
      associated_financial_account_ids: [receivable_id]
    }
  }
  response = multi_party_post( "/entities/#{entity_id}/attachments",post_data)
  if response['attachment'][0] == "não pode ser vazio."
    raise "O arquivo anexado foi vazio: #{arquivo}"
  end
  response
end
apaga_conta_a_pagar(id, entity_id) click to toggle source
# File lib/myfinance/conta_a_pagar.rb, line 19
def self.apaga_conta_a_pagar(id, entity_id)
  ldelete "/entities/#{entity_id}/payable_accounts/#{id}.json"
end
apaga_conta_a_receber(id, entity_id) click to toggle source
# File lib/myfinance/conta_a_receber.rb, line 16
def self.apaga_conta_a_receber(id, entity_id)
  ldelete "/entities/#{entity_id}/receivable_accounts/#{id}.json"
end
apaga_webhook(id) click to toggle source
# File lib/myfinance/webhook.rb, line 10
def self.apaga_webhook(id)
  ldelete "/integrations/webhooks/#{id}.json"
end
atualiza_pessoa( people_id, pessoa ) click to toggle source
# File lib/myfinance/pessoa.rb, line 26
def self.atualiza_pessoa( people_id, pessoa )
  # Vou rezar para que de certo
  # people = { 'person' => pessoa }
  @everyone = nil
  lput "/people/#{people_id}.json", pessoa
end
busca_conta_a_pagar(entity_id, nfe_id, search_field = 'description') click to toggle source
# File lib/myfinance/conta_a_pagar.rb, line 8
def self.busca_conta_a_pagar(entity_id, nfe_id, search_field = 'description')
  raise 'Enitidade não informada!' unless entity_id
  lget "/entities/#{entity_id}/payable_accounts.json?search[#{search_field}_like]=#{nfe_id}"
end
categoria_id(nome) click to toggle source
# File lib/myfinance/categoria.rb, line 3
def self.categoria_id(nome)
  mid = nil
  categorias.each do | item |
    category = item['category']
    if category['full_name'] == nome
      mid = category['id']
      break
    end
  end
  mid
end
categorias() click to toggle source
# File lib/myfinance/categoria.rb, line 15
def self.categorias
  lget '/categories.json'
end
centro_de_custo_id(nome) click to toggle source
# File lib/myfinance/centro_receita_custo.rb, line 7
def self.centro_de_custo_id(nome)
  centro_id(nome,true)
end
centro_de_receita_id(nome) click to toggle source
# File lib/myfinance/centro_receita_custo.rb, line 3
def self.centro_de_receita_id(nome)
  centro_id(nome,false)
end
centro_id(nome, custo = nil) click to toggle source
# File lib/myfinance/centro_receita_custo.rb, line 11
def self.centro_id(nome, custo = nil)
  mid = nil
  centros(custo).each do | item |
    cc = item['classification_center']
    if cc['name'] == nome
      mid = cc['id']
      break
    end
  end
  mid
end
centros(custo = nil) click to toggle source
# File lib/myfinance/centro_receita_custo.rb, line 23
def self.centros(custo = nil)
  items = Array.new
  classification_centers.each do | item |
    cc = item['classification_center']
    if custo.nil?
      items.push(item)
    else
      if custo
        if cc['cost_center']
          items.push(item)
        end
      else
        if cc['revenue_center']
          items.push(item)
        end
      end
    end
  end
  items
end
classification_centers() click to toggle source
# File lib/myfinance/centro_receita_custo.rb, line 44
def self.classification_centers
  centers = []
  for page in 1..50
    response = lget "/classification_centers.json?page=#{page}"
    break if response.empty?
    centers = centers.concat response
  end
  centers
end
conta_a_pagar(id, entity_id) click to toggle source
# File lib/myfinance/conta_a_pagar.rb, line 23
def self.conta_a_pagar(id, entity_id)
  lget "/entities/#{entity_id}/payable_accounts/#{id}.json"
end
conta_a_receber(id, entity_id) click to toggle source
# File lib/myfinance/conta_a_receber.rb, line 12
def self.conta_a_receber(id, entity_id)
  lget "/entities/#{entity_id}/receivable_accounts/#{id}.json"
end
conta_deposito_id(entity_id, nome) click to toggle source
# File lib/myfinance/conta_deposito.rb, line 7
def self.conta_deposito_id(entity_id, nome)
  contas_deposito(entity_id).each do | item |
    conta = item["deposit_account"]
    if conta["name"].strip.downcase == nome.strip.downcase
      return conta["id"]
      break
    end
  end
  nil
end
contas_deposito(entity_id) click to toggle source
# File lib/myfinance/conta_deposito.rb, line 3
def self.contas_deposito(entity_id)
  lget "/entities/#{entity_id}/deposit_accounts.json"
end
contas_deposito_like(entity_id, like_str) click to toggle source
# File lib/myfinance/conta_deposito.rb, line 18
def self.contas_deposito_like(entity_id, like_str)
  contas = []
  contas_deposito(entity_id).each do | item |
    conta = item["deposit_account"]
    if conta["name"].strip.downcase.include?(like_str.downcase)
      contas << conta
    end
  end
  contas
end
cria_conta_a_pagar(entity_id,pagamento) click to toggle source
# File lib/myfinance/conta_a_pagar.rb, line 13
def self.cria_conta_a_pagar(entity_id,pagamento)
  raise 'Enitidade não informada!' unless entity_id
  response = lpost "/entities/#{entity_id}/payable_accounts.json", parametro_conta_a_pagar(pagamento)
  response
end
cria_conta_a_pagar_entidade(nome_da_entidade,faturamento) click to toggle source
# File lib/myfinance/conta_a_pagar.rb, line 3
def self.cria_conta_a_pagar_entidade(nome_da_entidade,faturamento)
  entity_id = entidade_id(nome_da_entidade)
  cria_conta_a_pagar(entity_id,faturamento)
end
cria_conta_a_receber(entity_id, faturamento) click to toggle source
# File lib/myfinance/conta_a_receber.rb, line 7
def self.cria_conta_a_receber(entity_id, faturamento)
  lpost "/entities/#{entity_id}/receivable_accounts.json",
        parametro_conta_a_receber(faturamento)
end
cria_conta_a_receber_entidade(nome_da_entidade,faturamento) click to toggle source
# File lib/myfinance/conta_a_receber.rb, line 2
def self.cria_conta_a_receber_entidade(nome_da_entidade,faturamento)
  entity_id = entidade_id(nome_da_entidade)
  cria_conta_a_receber(entity_id,faturamento)
end
cria_e_anexa_arquivo(entity_id, receivable_id, nome_do_arquivo, conteudo_do_arquivo) click to toggle source
# File lib/myfinance/anexo.rb, line 5
def self.cria_e_anexa_arquivo(entity_id, receivable_id, nome_do_arquivo, conteudo_do_arquivo)
  file = nome_do_arquivo.split('.')
  #:encoding => 'ascii-8bit' -- na verdade não altere o arquivo original
  attached_file = Tempfile.new([file[0], ".#{file[1]}"])
  attached_file << conteudo_do_arquivo.encode('UTF-8', :invalid => :replace, :undef => :replace )
  attached_file.rewind
  response = anexa_arquivo(entity_id, receivable_id, nome_do_arquivo, attached_file)
  # attached_file.close
  # attached_file.unlink
  response
end
cria_pessoa( pessoa ) click to toggle source
# File lib/myfinance/pessoa.rb, line 19
def self.cria_pessoa( pessoa )
  # Vou rezar para que de certo
  @everyone = nil
  people = { 'person' => pessoa }
  lpost '/people.json', people
end
cria_webhook(webhook) click to toggle source
# File lib/myfinance/webhook.rb, line 2
def self.cria_webhook(webhook)
  lpost "/integrations/webhooks.json", webhook
end
desfaz_recebimento_de_conta_a_receber(id, entity_id) click to toggle source
# File lib/myfinance/conta_a_receber.rb, line 29
def self.desfaz_recebimento_de_conta_a_receber(id, entity_id)
  lput "/entities/#{entity_id}/receivable_accounts/#{id}/undo_receivement.json", {}
end
entidade(nome) click to toggle source
# File lib/myfinance/entidade.rb, line 15
def self.entidade(nome)
  mid = entidade_id(nome)
  response = lget "/entities/#{mid}.json"
  response['entity']
end
entidade_id(nome) click to toggle source
# File lib/myfinance/entidade.rb, line 3
def self.entidade_id(nome)
  mid = nil
  entidades.each do | ent |
    cliente = ent['entity']
    if cliente['name'] == nome or cliente['federation_subscription_number'] == nome
      mid = cliente['id']
      break
    end
  end
  mid
end
entidades() click to toggle source
# File lib/myfinance/entidade.rb, line 21
def self.entidades
  lget '/entities.json'
end
imposto_id(nome) click to toggle source
# File lib/myfinance/imposto.rb, line 3
def self.imposto_id(nome)
  mid = nil
  response = lget '/taxes.json'
  response.each do | item |
    imposto = item['tax']
    if imposto['name'] == nome
      mid = imposto['id']
      break
    end
  end
  mid
end
pesquisa_pessoa(campo, valor) click to toggle source
# File lib/myfinance/pessoa.rb, line 14
def self.pesquisa_pessoa(campo, valor)
  people =  Myfinance.lget URI.encode("/people.json?search[#{campo}]=#{valor}")
  people.empty? ? nil : people[0]["person"]
end
pessoa(cnpj_ou_nome) click to toggle source
# File lib/myfinance/pessoa.rb, line 8
def self.pessoa(cnpj_ou_nome)
  person = pesquisa_pessoa("federation_subscription_number_equals", cnpj_ou_nome)
  person ||= pesquisa_pessoa("name_equals", cnpj_ou_nome)
  person
end
pessoa_id(cnpj_ou_nome) click to toggle source
# File lib/myfinance/pessoa.rb, line 3
def self.pessoa_id(cnpj_ou_nome)
  person = pessoa(cnpj_ou_nome)
  person.nil? ? nil : person["id"]
end
recebe_conta_a_receber(id, entity_id, faturamento) click to toggle source
# File lib/myfinance/conta_a_receber.rb, line 24
def self.recebe_conta_a_receber(id, entity_id, faturamento)
  lput "/entities/#{entity_id}/receivable_accounts/#{id}/receive.json",
       parametro_conta_a_receber(faturamento)
end
setup(token, production=false, account=nil, logger=nil) click to toggle source

se o usuario tiver mais de um account e não informarmos o account id, ele pega o primeiro se tiver mais de um, precisamos informar

# File lib/myfinance.rb, line 27
def self.setup(token, production=false, account=nil, logger=nil)
  logger(logger, :info, :curl) if logger

  if production
    @endpoint = 'https://app.myfinance.com.br'
  else
    @endpoint = 'https://sandbox.myfinance.com.br'
    # @endpoint = 'https://app.myfinance.com.br'
  end
  base_uri @endpoint
  @token = token
  # testo com uma chamada simples
  response = accounts
  # Resposta deve ser um array de hashes
  unless response.code == 200
    raise "Erro ao inicializar a API do MyFinance: #{response.code} : #{response.parsed_response}"
  end
  if account and account.is_a?(String)
    @account_id = account_id(account)
  # else
  #   @account_id = get_account_id(account, response)
  end
end
webhooks() click to toggle source
# File lib/myfinance/webhook.rb, line 6
def self.webhooks
  lget "/integrations/webhooks.json"
end

Private Class Methods

add_account_id(options) click to toggle source
# File lib/myfinance.rb, line 129
def self.add_account_id(options)
  options[:headers]['ACCOUNT_ID'] = @account_id.to_s if @account_id
end
format_time(dt) click to toggle source
# File lib/myfinance.rb, line 125
def self.format_time(dt)
  dt.strftime('%FT%H:%MZ') rescue nil
end
get_account_id(account_id, accounts_response) click to toggle source
# File lib/myfinance.rb, line 133
def self.get_account_id(account_id, accounts_response)
  return account_id if account_id
  qtd_de_contas =  accounts_response.size
  raise 'Esse usuário não tem uma Conta associada ao seu usuário, por favor defina qual conta usar no acesso da API' if qtd_de_contas == 0
  raise 'Esse usuário tem mais de uma Conta associada ao seu usuário, por favor defina qual conta usar no acesso da API' if qtd_de_contas > 1
  accounts_response.first['account']['id']
end
header_info() click to toggle source
# File lib/myfinance.rb, line 65
def self.header_info
  # { 'Content-Type' => 'application/json', 'Accept' => 'application/json' }
  { 'Content-Type' => 'application/json' }
end
ldelete(url) click to toggle source
# File lib/myfinance.rb, line 115
def self.ldelete(url)
  options = {
      :basic_auth => {:username => @token, :password => 'x'},
      :headers => header_info
  }
  add_account_id options
  response = delete url, options
  response
end
lget(url) click to toggle source
# File lib/myfinance.rb, line 70
def self.lget(url)
  options = {
      :basic_auth => {:username => @token, :password => 'x'},
      :headers => header_info
  }
  add_account_id options
  get url, options
end
lpost(url,post_data) click to toggle source
# File lib/myfinance.rb, line 79
def self.lpost(url,post_data)
  options = {
      :basic_auth => {:username => @token, :password => 'x'},
      :body => post_data.to_json,
      :headers => header_info
  }
  add_account_id options
  response = post url, options
  response
end
lput(url,post_data) click to toggle source
# File lib/myfinance.rb, line 104
def self.lput(url,post_data)
  options = {
      :basic_auth => {:username => @token, :password => 'x'},
      :body => post_data.to_json,
      :headers => header_info
  }
  add_account_id options
  response = put url, options
  response
end
multi_party_post(url,post_data) click to toggle source
# File lib/myfinance.rb, line 90
def self.multi_party_post(url,post_data)
  options = {
      :basic_auth => {:username => @token, :password => 'x'},
      :body => post_data,
      :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json' },
      :detect_mime_type => true
  }
  add_account_id options
  # puts options.inspect
  response = post url, options
  response
end
parametro_conta_a_pagar(pagamento) click to toggle source
# File lib/myfinance/conta_a_pagar.rb, line 27
def self.parametro_conta_a_pagar(pagamento)
  {
      'payable_account' => pagamento
  }
end
parametro_conta_a_receber(faturamento) click to toggle source
# File lib/myfinance/conta_a_receber.rb, line 33
def self.parametro_conta_a_receber(faturamento)
  receivable_account = {
    'receivable_account' => faturamento
  }
end

Public Instance Methods

set_account_id(account_id) click to toggle source
# File lib/myfinance.rb, line 55
def set_account_id(account_id)
  @account_id = account_id
end
set_account_id_by_name(account_name) click to toggle source
# File lib/myfinance.rb, line 59
def set_account_id_by_name(account_name)
  @account_id = Myfinance.account_id(account_name)
end