Class: Fdis::Facturacion

Inherits:
Config
  • Object
show all
Defined in:
lib/fdis/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 Config

#cer_cadena, #initialize, #key_to_pem, #serial_number

Constructor Details

This class inherits a constructor from Fdis::Config

Instance Method Details

#cancela_doc(params = {}) ⇒ Object

end



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
# File 'lib/fdis/facturacion.rb', line 406

def cancela_doc(params={})
	# Sample params
	# params = {
	# 	uuid: '',
	# 	rfc_emisor: '',
	# 	motivo: '02',
	# 	key_password: '', # optional
	# 	cer_cadena: '', # optional
	# 	key_pem: '' # optional
	# }

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


	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),
		"motivo": '02',
		"b64Cer": params.fetch(:cer_cadena, @cadena), 
		"b64Key": params.fetch(:key_pem, @pem_cadena) 
	})

	req_options = {
     use_ssl: uri.scheme == "https",
   }

	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
179
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
# File 'lib/fdis/facturacion.rb', line 5

def comp_pago(params={})
	# Sample params
	# params = {
	# 	uuid: '',
	# 	folio: '',
	#   cp: '',
	# 	receptor_razon: 'Car zone',
	#   receptor_rfc: 'XAXX010101000',
	#   receptor_cp: '47180',
	#   receptor_regimen: '616',
	#   iva_id: 16,8,0,
	#   forma_pago: '01',
	#   total: 100.00,
	# 	time_pago: '',
	# 	time_now: '',
	# 	modena: '',
	# 	line_items: [
	# 		{
	# 			monto: 60.00,
	# 			moneda: '',
	#       id: ,
	# 		},
	# 	]
	# }

	puts " Datos --------"
	puts "-- Total params: #{params[:total]}"
	puts "--- Line items: "
	params[:line_items].each do |line|
		puts "--- #{line[:monto]}"
	end
	lines_total = params[:line_items].inject(0) {|sum, x| sum + x[:monto].to_f}

	puts "-- Suma de line_items: #{lines_total.round(2)}"

	if (lines_total.round(2) > params[:total].to_f)
		raise 'Error Fdis - la suma de los complementos de pago es mayor al total reportado' 
	end

	unless params[:time_pago] and params[:time_pago].size > 0
		raise "Error Fdis - la fecha de timbrado debe de estar presente"
	end



	
	time_now = params.fetch(:time_now, (Time.now).strftime("%Y-%m-%dT%H:%M:%S"))
	time_pago = params[:time_pago]


	base_doc = %(<?xml version="1.0" encoding="UTF-8"?>
		<cfdi:Comprobante xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:pago20="http://www.sat.gob.mx/Pagos20" xsi:schemaLocation="http://www.sat.gob.mx/Pagos20 http://www.sat.gob.mx/sitio_internet/cfd/Pagos/Pagos20.xsd http://www.sat.gob.mx/cfd/4 http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd" Version="4.0" Serie="" Folio="" Fecha="" Sello="" NoCertificado="" Certificado="" SubTotal="0" Moneda="XXX" Total="0" TipoDeComprobante="P" Exportacion="01" LugarExpedicion="" xmlns:cfdi="http://www.sat.gob.mx/cfd/4">

			<cfdi:Emisor Rfc="" Nombre="" RegimenFiscal="" />
			<cfdi:Receptor Rfc="" Nombre="" UsoCFDI="CP01" DomicilioFiscalReceptor="" RegimenFiscalReceptor="616" />

			<cfdi:Conceptos>
				<cfdi:Concepto ClaveProdServ="84111506" Cantidad="1" ClaveUnidad="ACT" Descripcion="Pago" ValorUnitario="0" Importe="0" ObjetoImp="01" />
			</cfdi:Conceptos>

			<cfdi:Complemento>

				<pago20:Pagos Version="2.0">
					<pago20:Totales MontoTotalPagos="" />

					<pago20:Pago FechaPago="" FormaDePagoP="01" MonedaP="MXN" Monto="">
					</pago20: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[:folio].to_s
	comprobante['Fecha'] = time_now
	comprobante['LugarExpedicion'] = params[:cp].to_s
	comprobante['NoCertificado'] = @serial
	comprobante['Certificado'] = @cadena

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

	# Receptor datos
	receptor = xml.at_xpath("//cfdi:Receptor")
	receptor['Nombre'] = params[:receptor_razon].to_s
	receptor['Rfc'] = params[:receptor_rfc].to_s
	receptor['DomicilioFiscalReceptor'] = params[:receptor_cp].to_s
	receptor['RegimenFiscalReceptor'] = params[:receptor_regimen].to_s

	# totales
	total = params[:total].to_f
	iva_id = params.fetch(:iva_id, 16)

	pago_totales = xml.at_xpath("//pago20:Totales")
	pago_totales['MontoTotalPagos'] = total.round(2).to_s # total


	if iva_id == 0
		subtotal = total
		iva = 0.00

		pago_totales['TotalTrasladosBaseIVA0'] = subtotal.round(2).to_s # subtotal
		pago_totales['TotalTrasladosImpuestoIVA0'] =  iva.round(2).to_s # iva

	elsif iva_id == 8
		subtotal = total / 1.08
		iva = total - subtotal

		pago_totales['TotalTrasladosBaseIVA8'] = subtotal.round(2).to_s # subtotal
		pago_totales['TotalTrasladosImpuestoIVA8'] =  iva.round(2).to_s # iva
	else
		subtotal = total / 1.16
		iva = total - subtotal

		pago_totales['TotalTrasladosBaseIVA16'] = subtotal.round(2).to_s # subtotal
		pago_totales['TotalTrasladosImpuestoIVA16'] =  iva.round(2).to_s # iva
	end

	# pago
	child_pago = xml.at_xpath("//pago20:Pago")
	child_pago['FechaPago'] = time_pago
	child_pago['FormaDePagoP'] = params[:forma_pago].to_s
	child_pago['MonedaP'] = params.fetch(:moneda, 'MXN')
	child_pago['Monto'] = total.round(2).to_s

	saldo_anterior = total

	params[:line_items].each_with_index do |line, index|
		monto = line[:monto].to_f
		child_pago_relacionado = Nokogiri::XML::Node.new "pago20:DoctoRelacionado", xml
		child_pago_relacionado['IdDocumento'] = params[:uuid]
		child_pago_relacionado['Serie'] = "Depo"
		child_pago_relacionado['Folio'] = line[:id].to_s

		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).round(2).to_s
		child_pago_relacionado['ImpPagado'] = monto.round(2).to_s
		child_pago_relacionado['ImpSaldoInsoluto'] = (saldo_anterior - monto).round(2).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 cadenaoriginal_4_0.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 '------ Fdis: comprobante de pago antes de timbre -------'
	puts xml.to_xml
	base64_xml = Base64.encode64(xml.to_xml)

	# haciendo llamada a API
	uri = URI("#{Fdis::UrlPro}/Timbrar40")
	request = Net::HTTP::Post.new(uri)
	# request.basic_auth(token, "")
	request.content_type = "application/json"
	# request["cache-control"] = 'no-cache'
	request.body = JSON.dump({
		"testMode": !@production,
		"idServicio": @id_servicio,
		"base64XmlFile": base64_xml,
	})

	req_options = {
     use_ssl: uri.scheme == "https",
   }

	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)

	case json_response
   when Net::HTTPSuccess, Net::HTTPRedirection
   	if response['success'] == true
   		decoded_xml = Nokogiri::XML(Base64.decode64(response['base64XmlFile']))
			# timbre = decoded_xml.at_xpath("//cfdi:Complemento").children[1]
			timbre = decoded_xml.at_xpath("//tfd:TimbreFiscalDigital")
			response = {
				status: 200,
				message_error: '',
				xml: decoded_xml.to_xml,
				uuid: timbre['UUID'],
				fecha_timbrado: timbre['FechaTimbrado'],
				sello_cfd: timbre['SelloCFD'],
				sello_sat: timbre['SelloSAT'],
				no_certificado_sat: timbre['NoCertificadoSAT'],
			}
			return response
		else
			response = {
				status: 400,
				message_error: "Error: #{response['errorMessages']}",
				xml: '',
				uuid: '',
				fecha_timbrado: '',
				sello_cfd: '',
				sello_sat: '',
				no_certificado_sat: '',
			}
			return response

   	end
   else
   	response = {
			status: json_response.code,
			message_error: "Error: #{json_response.message}",
			xml: '',
			uuid: '',
			fecha_timbrado: '',
			sello_cfd: '',
			sello_sat: '',
			no_certificado_sat: '',
		}
		return response

   end


end

#timbra_doc(params = {}) ⇒ Object



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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
# File 'lib/fdis/facturacion.rb', line 475

def timbra_doc(params={})
	### sample params
	# 
	# params = {
	# 	moneda: 'MXN',
	# 	series: 'FA',
	# 	folio: '003',
	# 	forma_pago: '',
	# 	metodo_pago: 'PUE',
	# 	cp: '47180',
	# 	receptor_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,
	#       retencion_iva: 0, 6, 16
	#  			# Optional parameters
	# 		},
	# 	]

	# }
	
	puts "---- Fdis:facturacion:timbra_doc"

	puts "--- Fdis: Datos --------"
	puts "--- Fdis: Line items: "
	params[:line_items].each do |line|
		puts "----- valor unitario: #{line[:valor_unitario]}"
		puts "----- cantidad: #{line[:cantidad]}"
	end

	time = params.fetch(:time, (Time.now).strftime("%Y-%m-%dT%H:%M:%S"))


	base_doc = %(<?xml version="1.0" encoding="utf-8"?>
	<cfdi:Comprobante xsi:schemaLocation="http://www.sat.gob.mx/cfd/4 http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd" Version="4.0" xmlns:cfdi="http://www.sat.gob.mx/cfd/4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Fecha="" Serie="" Folio="" FormaPago="" SubTotal="" Moneda="MXN" Total="" TipoDeComprobante="I" MetodoPago="" LugarExpedicion="" Certificado="" NoCertificado="" Sello="" >

		<cfdi:Emisor Rfc="" Nombre="" RegimenFiscal="" />
		<cfdi:Receptor Rfc="" Nombre="" DomicilioFiscalReceptor="" RegimenFiscalReceptor="" UsoCFDI="" />

		<cfdi:Conceptos></cfdi:Conceptos>
		<cfdi:Impuestos></cfdi:Impuestos>

	</cfdi:Comprobante>)

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

	xml = Nokogiri::XML(base_doc)
	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.to_s
	comprobante['FormaPago'] = params.fetch(:forma_pago, '01')
	comprobante['MetodoPago'] = params.fetch(:metodo_pago, 'PUE')
	comprobante['LugarExpedicion'] = params.fetch(:cp, '47180')
	comprobante['NoCertificado'] = @serial
	comprobante['Certificado'] = @cadena

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

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

	# retencion_iva = params.fetch(:retencion_iva, 0)

	impuestos = xml.at_xpath("//cfdi:Impuestos")
	traslados = Nokogiri::XML::Node.new "cfdi:Traslados", xml


	puts '--- Fdis time -----'
	puts time
	puts '--------'

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

	line_items = params[:line_items]

	suma_total = 0.00
	subtotal = 0.00
	suma_iva = 0.00
	suma_ret = 0.00

	line_items.each do |line|
		ret_iva = line.fetch(:retencion_iva, 0)
		puts ret_iva


		## revisando si la linea tiene iva 0
		if line[:tax_included] == true
			# if line[:tipo_impuesto] == '004'
			# 	valor_unitario = (line[:valor_unitario].to_f)
			# else
			# end
			valor_unitario = ((line[:valor_unitario]).to_f) / 1.16
		else
			valor_unitario = (line[:valor_unitario].to_f)
		end

		cantidad = line[:cantidad].to_f
		total_line = cantidad * valor_unitario

		# if line[:tipo_impuesto] == '004'
			# total_acumulator = cantidad * valor_unitario
		# else
			# total_acumulator = cantidad * valor_unitario * 1.16
		# end
		
		total_acumulator = cantidad * valor_unitario * 1.16

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

		puts "--- 01"
		## calculando retencion de IVA en caso de tener
		if ret_iva > 0
			if ret_iva == 6
					importe_ret_linea = (total_line * 1.06) - total_line
			elsif ret_iva == 16
				importe_ret_linea = importe_iva
			end
		else
			importe_ret_linea = 0
		end
		puts "--- 02"
		suma_ret += importe_ret_linea
			

		## Creando y poblando CFDI:CONCEPTO
		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'] = valor_unitario.round(4).to_s
		child_concepto['Importe'] = total_line.round(4).to_s
		child_concepto['ObjetoImp'] = '02'


		## Creando cdfi:Impuestos para cada linea
		child_impuestos = Nokogiri::XML::Node.new "cfdi:Impuestos", xml

		## Creando cfdi:Traslados para cada linea
		child_traslados = Nokogiri::XML::Node.new "cfdi:Traslados", xml
		child_traslado = Nokogiri::XML::Node.new "cfdi:Traslado", xml
		child_traslado['Base'] = total_line.round(4).to_s
		child_traslado['Importe'] = importe_iva.round(4).to_s
		child_traslado['Impuesto'] = '002'
		child_traslado['TasaOCuota'] = '0.160000'
		child_traslado['TipoFactor'] = "Tasa"

		# if line[:tipo_impuesto] == '004'
		# 	child_traslado['TasaOCuota'] = '0.000000'
		# else 
		# end


		# 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)
		
		## Creando cfdi:Retenciones para cada linea en caso de tener
		if ret_iva > 0
			child_retenciones = Nokogiri::XML::Node.new "cfdi:Retenciones", xml
			child_retencion = Nokogiri::XML::Node.new "cfdi:Retencion", xml
			child_retencion['Base'] = total_line.round(4).to_s
			child_retencion['Impuesto'] = '002'
			child_retencion['TipoFactor'] = "Tasa"

			if ret_iva == 6
				child_retencion['TasaOCuota'] = "0.060000"
			elsif ret_iva == 16
				child_retencion['TasaOCuota'] = "0.160000"
			end

			child_retencion['Importe'] = importe_ret_linea.round(4).to_s

			child_retenciones.add_child(child_retencion)
			child_impuestos.add_child(child_retenciones)
		end


	end

	puts '------ Totales -----'
	puts "Total suma = #{suma_total.round(2)}"
	puts "SubTotal suma = #{subtotal.round(2)}"
	puts "Suma iva = #{suma_iva.round(2)}"
	puts "Suma restenciones = #{suma_ret.round(2)}"

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


	## Poblanco cfdi:Impuestos
	impuestos['TotalImpuestosRetenidos'] = suma_ret.round(2).to_s if suma_ret > 0
	impuestos['TotalImpuestosTrasladados'] = suma_iva.round(2).to_s

	## filling default retencion info
	if suma_ret > 0
		retenciones = Nokogiri::XML::Node.new "cfdi:Retenciones", xml
		retencion_child = Nokogiri::XML::Node.new "cfdi:Retencion", xml
		retencion_child['Impuesto'] = "002"
		retencion_child['Importe'] = suma_ret.round(2).to_s
		# retencion_child['TipoFactor'] = "Tasa"

		retenciones.add_child(retencion_child)
		impuestos.add_child(retenciones)
		comprobante['Total'] = (suma_total - suma_ret).round(2).to_s
	else
		comprobante['Total'] = suma_total.round(2).to_s
	end


	## filling traslado info
	traslado_child = Nokogiri::XML::Node.new "cfdi:Traslado", xml
	traslado_child['Base'] = subtotal.round(2)
	traslado_child['Impuesto'] = '002'
	traslado_child['Importe'] = suma_iva.round(2).to_s
	traslado_child['TipoFactor'] = 'Tasa'
	traslado_child['TasaOCuota'] = '0.160000'
	traslados.add_child(traslado_child)
	impuestos.add_child(traslados)



	# puts '------ Totales -----'
	# puts "Total suma = #{comprobante['Total']}"
	# puts "SubTotal suma = #{subtotal}"
	# puts "Suma iva = #{suma_iva}"
	# puts "Suma retenciones = #{impuestos['TotalImpuestosRetenidos']}" if suma_ret > 0



	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 cadenaoriginal_4_0.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 '---- Fdis: comprobante sin timbrar ------'
	puts xml.to_xml
	puts '-------------------------'

	base64_xml = Base64.encode64(xml.to_xml)

	# haciendo llamada a API
	uri = URI("#{Fdis::UrlPro}/Timbrar40")
	request = Net::HTTP::Post.new(uri)
	request.content_type = "application/json"
	request.body = JSON.dump({
		"testMode": !@production,
		"idServicio": @id_servicio,
		"base64XmlFile": base64_xml,
	})

	req_options = {
     use_ssl: uri.scheme == "https",
   }

	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 "-- #{json_response} --"

	response = JSON.parse(json_response.body)

	case json_response
   when Net::HTTPSuccess, Net::HTTPRedirection
   	if response['success'] == true
   		decoded_xml = Nokogiri::XML(Base64.decode64(response['base64XmlFile']))
			# timbre = decoded_xml.at_xpath("//cfdi:Complemento").children[1]
			timbre = decoded_xml.at_xpath("//tfd:TimbreFiscalDigital")
			response = {
				status: 200,
				message_error: '',
				xml: decoded_xml.to_xml,
				uuid: timbre['UUID'],
				fecha_timbrado: timbre['FechaTimbrado'],
				sello_cfd: timbre['SelloCFD'],
				sello_sat: timbre['SelloSAT'],
				no_certificado_sat: timbre['NoCertificadoSAT'],
			}
			return response
		else
			response = {
				status: 400,
				message_error: "Error: #{response['errorMessages']}",
				xml: '',
				uuid: '',
				fecha_timbrado: '',
				sello_cfd: '',
				sello_sat: '',
				no_certificado_sat: '',
			}
			return response

   	end
   else
   	response = {
			status: json_response.code,
			message_error: "Error: #{json_response.message}",
			xml: '',
			uuid: '',
			fecha_timbrado: '',
			sello_cfd: '',
			sello_sat: '',
			no_certificado_sat: '',
		}
		return response

   end


end

#timbra_doc_cero(params = {}) ⇒ Object



831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
# File 'lib/fdis/facturacion.rb', line 831

def timbra_doc_cero(params={})
	puts "---- Fdis:facturacion:timbra_doc_cero"
	# 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,
	#  			# Optional parameters
	# 		},
	# 	]

	# }

	uri = @production ? URI("#{Fdis::UrlProduction}cfdi33/stamp/customv1/b64") : URI("#{Fdis::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(Fdis::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, '1').to_s
	comprobante['Fecha'] = time.to_s
	comprobante['FormaPago'] = params.fetch(:forma_pago, '01')
	comprobante['MetodoPago'] = params.fetch(:metodo_pago, 'PUE')
	comprobante['LugarExpedicion'] = params.fetch(:cp, '55555')
	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, 'XAXX010101000')
	receptor['UsoCFDI'] = params.fetch(:uso_cfdi, 'G03')


	# impuestos = xml.at_xpath("//cfdi:Impuestos")
	# traslados = Nokogiri::XML::Node.new "cfdi:Traslados", xml


	puts '--- Fdis time -----'
	puts time
	puts '--------'

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

	line_items = params[:line_items]

	suma_total = 0.00

	line_items.each do |line|
		
		valor_unitario = line[:valor_unitario].to_f
		cantidad = line[:cantidad].to_f
		total_line = cantidad * valor_unitario

		suma_total += total_line 

		## Creando y poblando CFDI:CONCEPTO
		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'] = valor_unitario.round(4).to_s
		child_concepto['Importe'] = total_line.round(4).to_s


		# Joining all up
		conceptos.add_child(child_concepto)
	

	end

	puts '------ Totales -----'
	puts "Subtotal = #{suma_total}"
	puts "Total = #{suma_total}"

	comprobante['Moneda'] = params.fetch(:moneda, 'MXN')
	comprobante['SubTotal'] = suma_total.round(2).to_s
	comprobante['Total'] = suma_total.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 '---- Fdis GEM 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 "-- Fdis API reponse..."
	puts "-- Response code: #{json_response.code} --"
	puts "-- Response body: #{json_response.body} --"
	puts "-- Response message: #{json_response.message} --"

	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