Skip to content

Instantly share code, notes, and snippets.

@dcaliri
Last active August 29, 2015 13:55
Show Gist options
  • Save dcaliri/8744275 to your computer and use it in GitHub Desktop.
Save dcaliri/8744275 to your computer and use it in GitHub Desktop.
class Bill
def assign_rps_number_and_serial(save_it = nil)
rps = Bill.order(:rps_serial, :rps_number).where('rps_number IS NOT NULL').select(:rps_number, :rps_serial).last
number = rps.try(:rps_number) || 1
serial = rps.try(:rps_serial) || 'A'
self.rps_number, self.rps_serial = if number < 999999999999
[number + 1, serial]
else
[1, serial + 'A']
end
self.save if save_it
end
def make_nfe
info = self.organizer.billing_info
nfe = self.build_nfe(email: organizer.owner.email)
nfe.send_rps(
rps_serial: self.rps_serial,
rps_number: self.rps_number,
amount: self.amount,
cpf: (self.tax_identifier.length == 11 ? self.tax_identifier : ''),
cnpj: (self.tax_identifier.length == 14 ? self.tax_identifier : ''),
owner_name: info.owner_name,
street: info.street,
street_type: info.street_type,
street_number: info.street_number,
city: info.city,
state: info.state,
cep: info.zipcode.gsub(/\D*/, '')
)
if nfe.success?
nfe.set_organizer
nfe.save!
self.organizer.billing_info.verify!
end
end
def sanitize
self.update_column :tax_identifier, tax_identifier.gsub(/\D/, '')
end
end
class Nfe
def send_rps(opts = {})
retries = 0
begin
self.service_code ||= '06564'
self.details ||= 'Comissão por serviço'
self.email ||= 'example@example.com'
r = NfePaulistana::Gateway.new(CERTS).envio_rps(
cnpj_remetente: NFE[:cnpj],
inscricao_prestador: NFE[:ccm],
data_emissao: stringify_to_date(Time.zone.now),
email_tomador: self.email,
tipo_rps: 'RPS',
serie_rps: opts[:rps_serial],
status_rps: 'N',
valor_servicos: ('%.02f' % opts[:amount]),
aliquota_servicos: '0.05',
tributacao_rps: 'T',
numero_rps: opts[:rps_number].to_s,
cpf_tomador: opts[:cpf].to_s,
cnpj_tomador: opts[:cnpj].to_s,
codigo_servico: self.service_code.to_s,
discriminacao: self.details.to_s,
razao_tomador: opts[:owner_name].to_s,
#tp_logradouro: opts[:street_type].to_s,
#logradouro: opts[:street].to_s,
#nr_endereco: opts[:street_number].to_s,
#cidade: opts[:city].to_s,
#uf: opts[:state].to_s,
cep: opts[:cep].to_s
)
self.success = r.success?
self.response = r.retorno
self.number = r.number if r.success?
rescue Savon::SOAPFault
sleep 15
retries += 1
retry if retries <= 3
false
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment