require 'active_support/core_ext/array' module Biro module CredDefense class Response < BaseResponse def initialize(response) @body = response.body end def cpf text('nrcpf').gsub(/\D/, '') end def birthdate text('dtnascimento') end def mothers_name text('nomae') end def name text('nopessoa') end def income text('nrrenda') end def profession text('nrcbo') end def emails email = text('noemail') Array.wrap(email) end def receita_federal rf = data.dig('dmcomprovantereceita')&.first return nil unless rf { name: rf.dig('nopessoa'), status: rf.dig('nosituacao'), date: rf.dig('dhprocessamento'), death: text('boobito') } end def equities data.dig('dmlistaparticipacaosocietaria')&.map do |e| cpf = e.dig('nrdocumentosocio')&.gsub(/\D/, '') cnpj = e.dig('nrcnpj')&.gsub(/\D/, '') name = e.dig('nosocio')&.strip company = e.dig('norazaosocial')&.strip shares = e.dig('qtpercentualcapitalsocial') position = e.dig('noqualificacaosocio')&.strip since = e.dig('dtentradasociedade')&.strip { cpf: cpf, cnpj: cnpj, name: name, company: company, shares: shares, position: position, since: since, } end end def addresses data.fetch('dmlistaenderecos', nil).map do |a| parts = a['nologradouro'].split('-') street = parts[0]&.split[0..-2].join(' ') number = parts[0]&.split&.pop city_parts = a['cdibgemunicipio']&.split('/') city = city_parts && city_parts[0] state = city_parts && city_parts[1] { street: street, number: number, complement: parts[1]&.strip, city: city, state: state, zipcode: a['nrcep'] } end end def phones data.fetch('dmlistatelefones', nil).map do |p| parts = p['nrtelefone']&.split(' ') ddd = parts&.fetch(0, nil)&.gsub(/\D/, '') number = parts&.fetch(1) kind = (number.to_s[0] == '9' ? :mobile : :landline) if number { ddd: ddd, number: number, kind: kind } end end def success? error.blank? end def error if json['result'] == 'error' json['messages']&.first end end private def text(field) data.dig('dmlistapessoafisica', field).strip end def data json.dig('advancedsearch') end def json JSON.parse(@body) end end end end