Class: SwFac::Facturacion

Inherits:
Tools show all
Defined in:
lib/sw_fac/facturacion.rb

Instance Attribute Summary

Attributes inherited from Config

#cadena, #dev_token, #doc_cer_path, #doc_key_path, #key_pass, #pem, #pem_cadena, #production_token, #serial

Instance Method Summary collapse

Methods inherited from Tools

#consulta_no_certificado, #consulta_saldo, #valida_rfc

Methods inherited from Config

#cer_cadena, #initialize, #key_to_pem, #serial_number

Constructor Details

This class inherits a constructor from SwFac::Config

Instance Method Details

#cancela_doc(params = {}) ⇒ Object



325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/sw_fac/facturacion.rb', line 325

def cancela_doc(params={})
  # Sample params

  # params = {

  #  uuid: '',

  #  rfc_emisor: '',

  #  key_password: '', # optional

  #  cer_cadena: '', # optional

  #  key_pem: '' # optional

  # }


   uri = @production ? URI("#{SwFac::UrlProduction}cfdi33/cancel/csd") : URI("#{SwFac::UrlDev}cfdi33/cancel/csd")
   token = @production ? @production_token : @dev_token
  time = Time.now

  request = Net::HTTP::Post.new(uri)
   request["Authorization"] = "bearer #{token}"
   request.content_type = "application/json"
   request["Cache-Control"] = 'no-cache'
   request["Postman-Token"] = '30b35bb8-534d-51c7-6a5c-e2c98a0c9395'
   request.body = JSON.dump({
     'uuid': params[:uuid],
     "password": params.fetch(:key_password, @key_pass),
     "rfc": params.fetch(:rfc_emisor, @rfc),
     "b64Cer": params.fetch(:cer_cadena, @cadena), 
     "b64Key": params.fetch(:key_pem, @pem_cadena) 
   })

   req_options = {
     use_ssl: false,
   }

   json_response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
       http.request(request)
   end

   puts "-- #{json_response.code} --"
   puts "-- #{json_response.message} --"
   # puts "-- Body --"

   # puts json_response.body

   # puts '---'

   response = JSON.parse(json_response.body)

   if json_response.code == '200'
    decoded_xml = response['data']['acuse']

    response = {
      status: 200,
      message_error: '',
      xml: decoded_xml,
    }

    return response
  else

    response ={
      status: json_response.code,
      message_error: "Error message: #{json_response.message}, #{response['message']} #{response['error_details']}",
      xml: '',
    }

    return response
  end

end

#comp_pago(params = {}) ⇒ Object



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
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/sw_fac/facturacion.rb', line 5

def comp_pago(params={})
  # Sample params

  # params = {

  #  uuid: '',

  #  venta_folio: '',

  #   cp: '',

  #  receptor_razon: 'Car zone',

  # receptor_rfc: 'XAXX010101000',

  # forma_pago: '01',

  # total: 100.00,

  #  time: '',

  #  modena: '',

  #  line_items: [

  #    {

  #      monto: 60.00,

  #      moneda: '',

  #    },

  #  ]

  # }


  raise 'Error - la suma de los complementos de pago es mayor al total reportado' if (params[:line_items].inject(0) {|sum, x| sum + x[:monto].to_f }) > params[:total].to_f

  uri = @production ? URI("#{SwFac::UrlProduction}cfdi33/stamp/customv1/b64") : URI("#{SwFac::UrlDev}cfdi33/stamp/customv1/b64")
  token = @production ? @production_token : @dev_token
  time = params.fetch(:time, Time.now)

  base_doc = %(<?xml version="1.0" encoding="UTF-8"?>
       <cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:pago10="http://www.sat.gob.mx/Pagos" xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd http://www.sat.gob.mx/Pagos http://www.sat.gob.mx/sitio_internet/cfd/Pagos/Pagos10.xsd" Version="3.3" SubTotal="0" Total="0" Moneda="XXX" TipoDeComprobante="P" >
           <cfdi:Emisor />
           <cfdi:Receptor UsoCFDI="P01"/>
           <cfdi:Conceptos>
               <cfdi:Concepto ClaveProdServ="84111506" Cantidad="1" ClaveUnidad="ACT" Descripcion="Pago" ValorUnitario="0" Importe="0" />
           </cfdi:Conceptos>
           <cfdi:Complemento>
               <pago10:Pagos Version="1.0">
                   <pago10:Pago>
                   </pago10:Pago>
               </pago10:Pagos>
           </cfdi:Complemento>
       </cfdi:Comprobante>)

   base_doc.delete!("\n")
base_doc.delete!("\t")

xml = Nokogiri::XML(base_doc)
   comprobante = xml.at_xpath("//cfdi:Comprobante")
   comprobante['Serie'] = 'P'
   comprobante['Folio'] = params[:venta_folio].to_s
   comprobante['Fecha'] = time.strftime("%Y-%m-%dT%H:%M:%S")
   comprobante['LugarExpedicion'] = params[:cp].to_s
   comprobante['NoCertificado'] = @serial
   comprobante['Certificado'] = @cadena
   emisor = xml.at_xpath("//cfdi:Emisor")
   emisor['Rfc'] = @rfc
   emisor['Nombre'] = @razon
   emisor['RegimenFiscal'] = @regimen_fiscal
   receptor = xml.at_xpath("//cfdi:Receptor")
   receptor['Nombre'] = params[:receptor_razon].to_s
   receptor['Rfc'] = params[:receptor_rfc].to_s

   child_pago = xml.at_xpath("//pago10:Pago")
   child_pago['FechaPago'] = time.strftime("%Y-%m-%dT%H:%M:%S")
   child_pago['FormaDePagoP'] = params[:forma_pago].to_s
   child_pago['MonedaP'] = params.fetch(:moneda, 'MXN')
   child_pago['Monto'] = params[:total].round(2).to_s

   saldo_anterior = params[:total].to_f

   params[:line_items].each_with_index do |line, index|
    monto = line[:monto].to_f
    child_pago_relacionado = Nokogiri::XML::Node.new "pago10:DoctoRelacionado", xml
     child_pago_relacionado['IdDocumento'] = params[:uuid]
     child_pago_relacionado['MonedaDR'] = line.fetch(:moneda, 'MXN') 
     child_pago_relacionado['MetodoDePagoDR'] = 'PPD'
     child_pago_relacionado['NumParcialidad'] = (index + 1).to_s

     child_pago_relacionado['ImpSaldoAnt'] = (saldo_anterior).to_s
     child_pago_relacionado['ImpPagado'] = monto.round(2).to_s
     child_pago_relacionado['ImpSaldoInsoluto'] = (saldo_anterior - monto).to_s
     saldo_anterior -= monto 

     child_pago.add_child(child_pago_relacionado)
   end

   # puts '---------------- Xml resultante comprobante de pago -----------------------'

   # puts xml.to_xml

   # puts '--------------------------------------------------------'


   path = File.join(File.dirname(__FILE__), *%w[.. tmp])
  id = SecureRandom.hex

  FileUtils.mkdir_p(path) unless File.exist?(path)
File.write("#{path}/tmp_c_#{id}.xml", xml.to_xml)
xml_path = "#{path}/tmp_c_#{id}.xml"
  cadena_path = File.join(File.dirname(__FILE__), *%w[.. cadena cadena33.xslt])

  File.write("#{path}/pem_#{id}.pem", @pem)
  key_pem_url = "#{path}/pem_#{id}.pem"
  sello = %x[xsltproc #{cadena_path} #{xml_path} | openssl dgst -sha256 -sign #{key_pem_url} | openssl enc -base64 -A]
  comprobante['Sello'] = sello

  File.delete("#{xml_path}")
  File.delete("#{key_pem_url}")

  # puts '------ comprobante de pago antes de timbre -------'

  # puts xml.to_xml


base64_xml = Base64.encode64(xml.to_xml)
   request = Net::HTTP::Post.new(uri)
   request.basic_auth(token, "")
   request.content_type = "application/json"
   request["cache-control"] = 'no-cache'
   request.body = JSON.dump({
     "credentials" => {
         "id" => params[:venta_folio].to_s,
         "token" => token.to_s
     },
     "issuer" => {
         "rfc" => @rfc
     },
     "document" => {
       "ref-id": params[:venta_folio].to_s,
       "certificate-number": @serial,
       "section": "all",
       "format": "xml",
       "template": "letter",
       "type": "application/xml",
       "content": base64_xml
     }
   })

   req_options = {
     use_ssl: false,
   }

   json_response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
       http.request(request)
   end
   puts "-- #{json_response.code} --"
   puts "-- #{json_response.message} --"
   # puts "-- Body --"

   # puts json_response.body

   # puts '---'

   response = JSON.parse(json_response.body)

   if json_response.code == '200'
    decoded_xml = Nokogiri::XML(Base64.decode64(response['content']))
   timbre = decoded_xml.at_xpath("//cfdi:Complemento").children[1]
   response = {
      status: 200,
      message_error: '',
      xml: decoded_xml.to_xml,
      uuid: response['uuid'],
      fecha_timbrado: timbre['FechaTimbrado'],
      sello_cfd: timbre['SelloCFD'],
      sello_sat: timbre['SelloSAT'],
      no_certificado_sat: timbre['NoCertificadoSAT'],
    }
    return response
  else
    response = {
      status: json_response.code,
      message_error: "Error message: #{json_response.message}, #{response['message']} #{response['error_details']}",
      xml: '',
      uuid: '',
      fecha_timbrado: '',
      sello_cfd: '',
      sello_sat: '',
      no_certificado_sat: '',
    }
    return response
  end

end

#nota_credito(params = {}) ⇒ Object



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# File 'lib/sw_fac/facturacion.rb', line 180

def nota_credito(params={})
  # Sample params

  # params = {

  #  uuid_relacionado: '',

  #   desc: '',

  #  motivo: 'dev, mod',

  #  series: '',

  #  folio: '',

  #  cp: '',

  #  time: '',

  #  receptor_razon: '',

#   receptor_rfc: '',

#   uso_cfdi: '',

  # }


  total = (params[:monto]).to_f
subtotal = total / 1.16
tax = total - subtotal

  uri = @production ? URI("#{SwFac::UrlProduction}cfdi33/stamp/customv1/b64") : URI("#{SwFac::UrlDev}cfdi33/stamp/customv1/b64")
  token = @production ? @production_token : @dev_token
  time = params.fetch(:time, Time.now)

  base_doc = %(<?xml version="1.0" encoding="utf-8"?>
  <cfdi:Comprobante xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd" Version="3.3" Serie="#{params.fetch(:series, 'N')}" Folio="#{params[:folio]}" Fecha="#{time.strftime("%Y-%m-%dT%H:%M:%S")}" FormaPago="99" NoCertificado="#{@serial}" Certificado="#{@cadena}" SubTotal="#{subtotal.round(2)}" Moneda="#{params.fetch(:moneda, 'MXN')}" Total="#{total.round(2)}" TipoDeComprobante="E" MetodoPago="PUE" LugarExpedicion="#{params[:cp]}" xmlns:cfdi="http://www.sat.gob.mx/cfd/3">
    <cfdi:CfdiRelacionados TipoRelacion="01">
      <cfdi:CfdiRelacionado UUID="#{params[:uuid_relacionado]}" />
    </cfdi:CfdiRelacionados>
    <cfdi:Emisor Rfc="#{@rfc}" Nombre="#{@razon}" RegimenFiscal="#{@regimen_fiscal}" />
    <cfdi:Receptor Rfc="#{params[:receptor_rfc]}" Nombre="#{params[:receptor_razon]}" UsoCFDI="#{params.fetch(:uso_cfdi, 'G03')}" />
    <cfdi:Conceptos>
      <cfdi:Concepto ClaveUnidad="ACT" ClaveProdServ="84111506" NoIdentificacion="C" Cantidad="1.00" Unidad="Pieza" Descripcion="#{params.fetch(:desc, 'DICTAMEN CC FACTURA ORIGEN 0')}" ValorUnitario="#{subtotal.round(2)}" Importe="#{subtotal.round(2)}">
        <cfdi:Impuestos>
          <cfdi:Traslados>
            <cfdi:Traslado Base="#{subtotal.round(2)}" Impuesto="002" TipoFactor="Tasa" TasaOCuota="0.160000" Importe="#{tax.round(2)}" />
          </cfdi:Traslados>
        </cfdi:Impuestos>
      </cfdi:Concepto>
    </cfdi:Conceptos>
    <cfdi:Impuestos TotalImpuestosTrasladados="#{tax.round(2)}">
      <cfdi:Traslados>
        <cfdi:Traslado Impuesto="002" TipoFactor="Tasa" TasaOCuota="0.160000" Importe="#{tax.round(2)}" />
      </cfdi:Traslados>
    </cfdi:Impuestos>
  </cfdi:Comprobante>
)

base_doc.delete!("\n")
base_doc.delete!("\t")

xml = Nokogiri::XML(base_doc)
  comprobante = xml.at_xpath("//cfdi:Comprobante")

  path = File.join(File.dirname(__FILE__), *%w[.. tmp])
  id = SecureRandom.hex

  FileUtils.mkdir_p(path) unless File.exist?(path)
File.write("#{path}/tmp_n_#{id}.xml", xml.to_xml)
xml_path = "#{path}/tmp_n_#{id}.xml"
  cadena_path = File.join(File.dirname(__FILE__), *%w[.. cadena cadena33.xslt])

  File.write("#{path}/pem_#{id}.pem", @pem)
  key_pem_url = "#{path}/pem_#{id}.pem"
  sello = %x[xsltproc #{cadena_path} #{xml_path} | openssl dgst -sha256 -sign #{key_pem_url} | openssl enc -base64 -A]
  comprobante['Sello'] = sello

  File.delete("#{xml_path}")
  File.delete("#{key_pem_url}")

  puts '------ nota antes de timbre -------'
  puts xml.to_xml

base64_xml = Base64.encode64(xml.to_xml)

  request = Net::HTTP::Post.new(uri)
  request.basic_auth(token, "")
  request.content_type = "application/json"
  request["cache-control"] = 'no-cache'
  request.body = JSON.dump({
    "credentials" => {
        "id" => "#{params[:folio]}",
        "token" => token
    },
    "issuer" => {
        "rfc" => @rfc
    },
    "document" => {
      "ref-id": "#{params[:folio]}",
      "certificate-number": @serial,
      "section": "all",
      "format": "xml",
      "template": "letter",
      "type": "application/xml",
      "content": base64_xml
    }
  })

  req_options = {
    use_ssl: false,
  }

  json_response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
      http.request(request)
  end


  puts "-- #{json_response.code} --"
  puts "-- #{json_response.message} --"
  # puts "-- Body --"

  # puts json_response.body

  # puts '---'

  response = JSON.parse(json_response.body)

  if json_response.code == '200'
    decoded_xml = Nokogiri::XML(Base64.decode64(response['content']))
   timbre = decoded_xml.at_xpath("//cfdi:Complemento").children.first

   response = {
      status: 200,
      message_error: '',
      xml: decoded_xml.to_xml,
      uuid: response['uuid'],
      fecha_timbrado: timbre['FechaTimbrado'],
      sello_cfd: timbre['SelloCFD'],
      sello_sat: timbre['SelloSAT'],
      no_certificado_sat: timbre['NoCertificadoSAT'],
    }
     return response
  else
    response = {
      status: json_response.code,
      message_error: "Error message: #{json_response.message}, #{response['message']} #{response['error_details']}",
      xml: '',
      uuid: '',
      fecha_timbrado: '',
      sello_cfd: '',
      sello_sat: '',
      no_certificado_sat: '',
    }
    return response
  end


end

#timbra_doc(params = {}) ⇒ Object



390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
# File 'lib/sw_fac/facturacion.rb', line 390

def timbra_doc(params={})
  ### sample params

  # 

  # params = {

  #  moneda: 'MXN',

  #  series: 'FA',

  #  folio: '003',

  #  forma_pago: '',

  #  metodo_pago: 'PUE',

  #  cp: '47180',

  #  receptor_razon: 'Car zone',

  #  receptor_rfc: '',

  #  uso_cfdi: 'G03',

  #   time: "%Y-%m-%dT%H:%M:%S",

  #  line_items: [

  #    {

  #      clave_prod_serv: '78181500',

 #        clave_unidad: 'E48',

 #        unidad: 'Servicio',

 #        sku: 'serv001',

 #        cantidad: 1,

 #        descripcion: 'Servicio mano de obra',

 #        valor_unitario: 100.00,

 #        descuento: 0.00,

 #        tax_included: true,

 #        # Optional parameters

 #        # tipo_impuesto: '002'

  #    },

  #  ]


  # }



   uri = @production ? URI("#{SwFac::UrlProduction}cfdi33/stamp/customv1/b64") : URI("#{SwFac::UrlDev}cfdi33/stamp/customv1/b64")
  token = @production ? @production_token : @dev_token
  time = params.fetch(:time, (Time.now).strftime("%Y-%m-%dT%H:%M:%S"))

  xml = Nokogiri::XML(SwFac::DocBase)
  comprobante = xml.at_xpath("//cfdi:Comprobante")
  comprobante['TipoCambio'] = '1'
  comprobante['TipoDeComprobante'] = 'I'
  comprobante['Serie'] = params.fetch(:series, 'FA').to_s
  comprobante['Folio'] = params.fetch(:folio).to_s
  comprobante['Fecha'] = time.strftime("%Y-%m-%dT%H:%M:%S")
  comprobante['FormaPago'] = params.fetch(:forma_pago, '01')
  comprobante['MetodoPago'] = params.fetch(:metodo_pago, 'PUE')
  comprobante['LugarExpedicion'] = params.fetch(:cp, '')
  comprobante['NoCertificado'] = @serial
  comprobante['Certificado'] = @cadena

  emisor = xml.at_xpath("//cfdi:Emisor")
  emisor['Nombre'] = @razon
  emisor['RegimenFiscal'] = @regimen_fiscal
  emisor['Rfc'] = @rfc

  receptor = xml.at_xpath("//cfdi:Receptor")
  receptor['Nombre'] = params.fetch(:receptor_razon, '')
  receptor['Rfc'] = params.fetch(:receptor_rfc, '')
  receptor['UsoCFDI'] = params.fetch(:uso_cfdi, 'G03')

  impuestos = xml.at_xpath("//cfdi:Impuestos")
  traslado = xml.at_xpath("//cfdi:Traslado")


  conceptos = xml.at_xpath("//cfdi:Conceptos")

  line_items = params[:line_items]

  suma_total = 0.00
  subtotal = 0.00
  suma_iva = 0.00

  line_items.each do |line|
    descuento = line.fetch(:descuento, 0.00).to_f

    if line[:tax_included] == true
      unitario = ((line[:valor_unitario]).to_f - descuento) / 1.16
    else
      unitario = (line[:valor_unitario].to_f) - descuento
    end

    cantidad = line[:cantidad].to_f
    total_line = cantidad * unitario
    total_acumulator = cantidad * unitario * 1.16
    importe_iva = total_acumulator - total_line 

    subtotal += total_line 
    suma_iva += importe_iva
    suma_total += total_acumulator 


    child_concepto = Nokogiri::XML::Node.new "cfdi:Concepto", xml
    child_concepto['ClaveProdServ'] = line[:clave_prod_serv].to_s
    child_concepto['NoIdentificacion'] = line[:sku].to_s 
    child_concepto['ClaveUnidad'] = line[:clave_unidad].to_s
    child_concepto['Unidad'] = line[:unidad].to_s
    child_concepto['Descripcion'] = line[:descripcion].to_s
    child_concepto['Cantidad'] = cantidad.to_s
    child_concepto['ValorUnitario'] = unitario.round(6).to_s
    child_concepto['Importe'] = total_line.round(6).to_s
    # child_concepto['Descuento'] = line.fetch(:descuento, 0.00).round(6).to_s


    child_impuestos = Nokogiri::XML::Node.new "cfdi:Impuestos", xml
    child_traslados = Nokogiri::XML::Node.new "cfdi:Traslados", xml
    child_traslado = Nokogiri::XML::Node.new "cfdi:Traslado", xml
    child_traslado['Base'] = total_line.round(6).to_s
    child_traslado['Impuesto'] = line.fetch(:tipo_impuesto, '002')
    child_traslado['TipoFactor'] = "Tasa"
    child_traslado['TasaOCuota'] = '0.160000'
    child_traslado['Importe'] = importe_iva.round(6).to_s
  
    # Joining all up

    child_traslados.add_child(child_traslado)
    child_impuestos.add_child(child_traslados)
    child_concepto.add_child(child_impuestos)

    conceptos.add_child(child_concepto)

  end

  puts '------ Line -----'
  puts "Total suma = #{suma_total}"
   puts "SubTotal suma = #{subtotal}"
   puts "Suma iva = #{suma_iva}"

  comprobante['SubTotal'] = subtotal.round(2).to_s
  comprobante['Total'] = suma_total.round(2).to_s
  comprobante['Moneda'] = params.fetch(:moneda, 'MXN')

  impuestos['TotalImpuestosTrasladados'] = suma_iva.round(2).to_s
  traslado['Importe'] = suma_iva.round(2).to_s

  path = File.join(File.dirname(__FILE__), *%w[.. tmp])
  id = SecureRandom.hex

  FileUtils.mkdir_p(path) unless File.exist?(path)
File.write("#{path}/tmp_#{id}.xml", xml.to_xml)
xml_path = "#{path}/tmp_#{id}.xml"
  cadena_path = File.join(File.dirname(__FILE__), *%w[.. cadena cadena33.xslt])

  # puts File.read(cadena_path)

  File.write("#{path}/pem_#{id}.pem", @pem)
  key_pem_url = "#{path}/pem_#{id}.pem"
  sello = %x[xsltproc #{cadena_path} #{xml_path} | openssl dgst -sha256 -sign #{key_pem_url} | openssl enc -base64 -A]
  comprobante['Sello'] = sello

  File.delete("#{xml_path}")
  File.delete("#{key_pem_url}")

  # puts '---- comprobante sin timbrar------'

  # puts xml.to_xml

  # puts '-------------------------'


  base64_xml = Base64.encode64(xml.to_xml)
  request = Net::HTTP::Post.new(uri)
  request.basic_auth(token, "")
  request.content_type = "application/json"
  request["cache-control"] = 'no-cache'
  request.body = JSON.dump({
    "credentials" => {
        "id" => params.fetch(:folio).to_s,
        "token" => token
    },
    "issuer" => {
        "rfc" => emisor['Rfc']
    },
    "document" => {
      "ref-id": params.fetch(:folio).to_s,
      "certificate-number": comprobante['NoCertificado'],
      "section": "all",
      "format": "xml",
      "template": "letter",
      "type": "application/xml",
      "content": base64_xml
    }
  })

  req_options = {
    use_ssl: false,
  }

  json_response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
      http.request(request)
  end

  puts "-- #{json_response.code} --"
  puts "-- #{json_response.message} --"
  # puts "-- Body --"

  # puts json_response.body

  # puts '---'

  response = JSON.parse(json_response.body)

  if json_response.code == '200'
    decoded_xml = Nokogiri::XML(Base64.decode64(response['content']))
    timbre = decoded_xml.at_xpath("//cfdi:Complemento").children.first

    response = {
      status: 200,
      message_error: '',
      xml: decoded_xml.to_xml,
      uuid: response['uuid'],
      fecha_timbrado: timbre['FechaTimbrado'],
      sello_cfd: timbre['SelloCFD'],
      sello_sat: timbre['SelloSAT'],
      no_certificado_sat: timbre['NoCertificadoSAT'],
    }

    return response
  else

    response ={
      status: json_response.code,
      message_error: "Error message: #{json_response.message}, #{response['message']} #{response['error_details']}",
      xml: '',
      uuid: '',
      fecha_timbrado: '',
      sello_cfd: '',
      sello_sat: '',
      no_certificado_sat: '',
    }

    return response
  end

end