m_cfdi 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 6a4f6145d69b6c02670db615dc5d83e810c77ebe
4
+ data.tar.gz: e658056476fabedbcf1c2936e5bdb45de5cbc688
5
+ SHA512:
6
+ metadata.gz: 7cd62893bf6c100cb869b3e35bc12b751f7c0faaa0f2b7bdd78d683515534dae0933d8bdd5a0244d96e7a1e333d013fcd0c633b39710aeae1e8aefa57fb9899a
7
+ data.tar.gz: 458b70122799bca1db0ab0350c0597d2d856b1d8d16bddc5e884f5e8d81f419c011a2743ba58c7ddb82c148a0bcf301b7e69cffb0184bb59330f6cd2c92dbee3
data/.gitignore ADDED
@@ -0,0 +1,36 @@
1
+ /Gemfile.lock
2
+ *.gem
3
+ *.rbc
4
+ /.config
5
+ /coverage/
6
+ /InstalledFiles
7
+ /pkg/
8
+ /spec/reports/
9
+ /test/tmp/
10
+ /test/version_tmp/
11
+ /tmp/
12
+
13
+ ## Specific to RubyMotion:
14
+ .dat*
15
+ .repl_history
16
+ build/
17
+
18
+ ## Documentation cache and generated files:
19
+ /.yardoc/
20
+ /_yardoc/
21
+ /doc/
22
+ /rdoc/
23
+
24
+ ## Environment normalisation:
25
+ /.bundle/
26
+ /vendor/bundle
27
+ /lib/bundler/man/
28
+
29
+ # for a library or gem, you might want to ignore these files since the code is
30
+ # intended to run in multiple environments; otherwise, check them in:
31
+ # Gemfile.lock
32
+ # .ruby-version
33
+ # .ruby-gemset
34
+
35
+ # unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
36
+ .rvmrc
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.2.3
4
+ before_install: gem install bundler -v 1.10.6
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in CFDI.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 MaSys Development
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
data/README.md ADDED
@@ -0,0 +1,185 @@
1
+ # CFDI
2
+ ### CFDI Mexico.
3
+
4
+ CFDI GEM, to generate XML file for invoice, all you have to do, is to send the xml string to your PAC and receive the final xml file then save it.
5
+
6
+ # Installation:
7
+
8
+ In your gem file:
9
+ ```git
10
+ gem 'm_cfdi' # NOT UPLOADED
11
+ ```
12
+
13
+ or
14
+
15
+ ```git
16
+ gem 'm_cfdi', git: 'https://github.com/MaSys/m_cfdi.git'
17
+ ```
18
+
19
+ or install it directly from your terminal:
20
+ ```git
21
+ gem install m_cfdi
22
+ ```
23
+
24
+ # Usage:
25
+
26
+ ```ruby
27
+
28
+ class Invoice
29
+ def initialize(args = {})
30
+ @invoice = args[:invoice] # assign invoice object from args.
31
+ @cer = args[:cer] # path to .cer file.
32
+ @pem = args[:pem] # path to .pem file.
33
+ @pass = args[:password] # password of .pem file.
34
+ invoice_cfdi
35
+ @invoice_cfdi.transmitter = transmitter # assign transmitter to invoice.
36
+ @invoice_cfdi.receptor = receptor # assign receptor to invoice.
37
+ add_concepts # add concepts to invoice.
38
+ add_taxes # add taxes to invoice.
39
+ certificate_invoice # create certificate and stamp for invoice.
40
+ end
41
+
42
+ def invoice_cfdi
43
+ @invoice_cfdi = MCFDI::Invoice.new(
44
+ folio: @invoice.folio, series: @invoice.series,
45
+ created_at: @invoice.created_at,
46
+ proof_type: I18n.t("invoice_proof_types.#{@invoice.proof_type}"),
47
+ payment_way: @invoice.payment_way,
48
+ payment_conditions: @invoice.payment_conditions,
49
+ payment_method: @invoice.payment_method,
50
+ expedition_place: @invoice.expedition_place,
51
+ total: @invoice.total, subtotal: @invoice.subtotal
52
+ )
53
+ end
54
+
55
+ def transmitter
56
+ { rfc: @invoice.seller.rfc, business_name: @invoice.seller.business_name,
57
+ address: address(@invoice.seller),
58
+ fiscal_regime: @invoice.seller.fiscal_regime }
59
+ end
60
+
61
+ def receptor
62
+ { rfc: @invoice.buyer.rfc, business_name: @invoice.buyer.business_name,
63
+ address: address(@invoice.buyer) }
64
+ end
65
+
66
+ def address(entity)
67
+ { street: entity.street, street_number: entity.street_number,
68
+ interior_number: entity.interior_number,
69
+ neighborhood: entity.neighborhood, location: entity.location,
70
+ reference: entity.reference, city: entity.city, state: entity.state,
71
+ country: entity.country, zip_code: entity.zip_code }
72
+ end
73
+
74
+ def add_concepts
75
+ @invoice.invoice_items.each do |ii|
76
+ @invoice_cfdi.concepts << MCFDI::Concept.new(
77
+ quantity: ii.quantity, measure_unit: ii.measure_unit,
78
+ code: ii.code, name: ii.name, price: ii.price, import: ii.import
79
+ )
80
+ end
81
+ end
82
+
83
+ def add_taxes
84
+ iva if @invoice.iva > 0
85
+ ieps if @invoice.ieps > 0
86
+ detained_iva if @invoice.detained_iva > 0
87
+ isr if @invoice.isr > 0
88
+ end
89
+
90
+ def iva
91
+ @invoice_cfdi.taxes.transferred << MCFDI::Transferred.new(
92
+ tax: 'IVA', rate: 16, import: @invoice.iva)
93
+ end
94
+
95
+ def ieps
96
+ @invoice_cfdi.taxes.transferred << MCFDI::Transferred.new(
97
+ tax: 'IEPS', rate: 12, import: @invoice.ieps)
98
+ end
99
+
100
+ def detained_iva
101
+ @invoice_cfdi.taxes.detained << MCFDI::Detained.new(
102
+ tax: 'IVA', rate: 16, import: @invoice.detained_iva)
103
+ end
104
+
105
+ def isr
106
+ @invoice_cfdi.taxes.detained << MCFDI::Detained.new(
107
+ tax: 'ISR', rate: 16, import: @invoice.isr)
108
+ end
109
+
110
+ # create certificate and stamp for invoice.
111
+ def certificate_invoice
112
+ certificate = MCFDI::Certificate.new(@cer)
113
+ key = MCFDI::Key.new(@pem, @pass)
114
+ certificate.certificate(@invoice_cfdi)
115
+ key.seal(@invoice_cfdi)
116
+ end
117
+
118
+ # return original string create by CFDI gem.
119
+ def original_string
120
+ @invoice_cfdi.original_string
121
+ end
122
+
123
+ # validate original string with schema.
124
+ def validate_original_string
125
+ @invoice_cfdi.validate_original_string
126
+ end
127
+
128
+ # return original string created by the schema.
129
+ def original_string_from_xslt
130
+ @invoice_cfdi.original_string
131
+ end
132
+
133
+ # return xml of the invoice and save it to file (before seal it with SAT).
134
+ def xml
135
+ file = File.new("#{@invoice.full_folio}-not-billed.xml", "wb")
136
+ file.write(@invoice_cfdi.to_xml)
137
+ file.close
138
+ @invoice_cfdi.to_xml
139
+ end
140
+
141
+ # validate xml with schema and return errors.
142
+ def validate_xml
143
+ @invoice_cfdi.validate_xml
144
+ end
145
+ end
146
+
147
+ ```
148
+
149
+ and then, you can call this class by:
150
+
151
+ ```ruby
152
+
153
+ @invoice = '{YOUR INVOICE OBJECT}'
154
+ @in = Invoice.new(
155
+ invoice: @invoice, cer: 'CERTIFICATION_FILE_PATH',
156
+ pem: 'PEM_FILE_PATH",
157
+ password: 'PASSWORD'
158
+ )
159
+ @in.xml
160
+ @in.original_string
161
+
162
+ ```
163
+
164
+ to generate your `.pem` file:
165
+
166
+ ```
167
+ openssl pkcs8 -inform DET -in aaa010101aaa.key -passin pass:12345678a -out key.pem
168
+ ```
169
+
170
+
171
+ # TODO:
172
+ * Create configuration class.
173
+
174
+
175
+ # Contributing
176
+
177
+ Fork it
178
+ 1. Create your feature branch (git checkout -b my-new-feature)
179
+
180
+ 2. Commit your changes (git commit -am 'Add some feature')
181
+
182
+ 3. Push to the branch (git push origin my-new-feature)
183
+
184
+ 4. Create new Pull Request
185
+
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "CFDI"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,13 @@
1
+ module MCFDI
2
+ # Address Class
3
+ class Addenda < Base
4
+ attr_accessor :name, :namespace, :xsd, :data
5
+
6
+ def initialize(args = {})
7
+ args.each do |key, value|
8
+ method = "#{key}="
9
+ send(method, value) if self.respond_to? method
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,42 @@
1
+ # street -> Calle
2
+ # street_number -> Numero Exterior
3
+ # interior_number -> Numero Interior
4
+ # neighborhood -> Colonia
5
+ # location -> Localidad
6
+ # reference -> Referencia
7
+ # city -> Municipio
8
+ # state -> Estado
9
+ # country -> Pais
10
+ # zip_code -> Codigo Postal
11
+
12
+ #
13
+ module MCFDI
14
+ # Address Class for transmitter and receptor.
15
+ class Address < Base
16
+ attr_accessor :street, :street_number, :interior_number, :neighborhood,
17
+ :location, :reference, :city, :state, :country, :zip_code
18
+
19
+ def initialize(args = {})
20
+ args.each { |key, value| send("#{key}=", value) }
21
+ end
22
+
23
+ # return original string (cadena original) of the address.
24
+ def original_string
25
+ c = []
26
+ self.attributes.each do |k|
27
+ v = send(k)
28
+ next unless v.present?
29
+ c << v
30
+ end
31
+ c
32
+ end
33
+
34
+ # return hash with values in spanish for the xml.
35
+ def to_x
36
+ { calle: @street, noExterior: @street_number,
37
+ noInterior: @interior_number, colonia: @neighborhood,
38
+ localidad: @location, referencia: @reference, municipio: @city,
39
+ estado: @state, pais: @country, codigoPostal: @zip_code }
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,25 @@
1
+ module MCFDI
2
+ class Base
3
+ def self.attr_accessor(*vars)
4
+ @attributes ||= []
5
+ @attributes.concat vars
6
+ super(*vars)
7
+ end
8
+
9
+ def self.attributes
10
+ @attributes
11
+ end
12
+
13
+ # return list of attr_accessors.
14
+ def attributes
15
+ self.class.attributes
16
+ end
17
+
18
+ # return hash of attributes with values.
19
+ def to_h
20
+ h = {}
21
+ attributes.each { |k| h[k] = send(k) }
22
+ h
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,36 @@
1
+ # certificate_number -> noCertificado
2
+
3
+ #
4
+ module MCFDI
5
+ require 'openssl'
6
+
7
+ # Certificate class to generate invoice certification from .cer.
8
+ class Certificate < OpenSSL::X509::Certificate
9
+
10
+ # Certificate Number
11
+ attr_reader :certificate_number
12
+ # Certificate in Base64
13
+ attr_reader :data
14
+
15
+ # Importar un certificado de sellado
16
+ # @param file [IO, String] El `path` del certificado o un objeto #IO
17
+ #
18
+ # @return [CFDI::Certificado] Un certificado
19
+ def initialize (file)
20
+ if file.is_a? String
21
+ file = File.read(file)
22
+ end
23
+ super file
24
+
25
+ @certificate_number = '';
26
+ self.serial.to_s(16).scan(/.{2}/).each { |v| @certificate_number += v[1]; }
27
+ @data = self.to_s.gsub(/^-.+/, '').gsub(/\n/, '')
28
+
29
+ end
30
+
31
+ def certificate(invoice)
32
+ invoice.certificate_number = @certificate_number
33
+ invoice.certificate = @data
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,24 @@
1
+ # UUID
2
+ # stamp_date = Fecha Timbrado
3
+ # cfd_stamp = sello CFD
4
+ # sat_certificate_num = noCertificadoSAT
5
+ # sat_stamp = selloSAT
6
+ # version
7
+
8
+ #
9
+ module MCFDI
10
+ # Complement Class
11
+ class Complement < Base
12
+
13
+ attr_accessor :uuid, :stamp_date, :cfd_stamp, :sat_certificate_num,
14
+ :sat_stamp, :version
15
+
16
+ # Regresa la cadena Original del Timbre Fiscal Digital del SAT
17
+ #
18
+ # @return [String] la cadena formada
19
+ def string
20
+ a = [@version, @uuid, @stamp_date, @cfd_stamp, @sat_certificate_num]
21
+ "||#{a.join('|')}||"
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,37 @@
1
+ # code -> noIdentificacion
2
+ # name -> Descripcion
3
+ # measure_unit -> Unidad
4
+ # quantity -> Cantidad
5
+ # price -> Precio Unitario
6
+ # importe -> Importe
7
+
8
+ #
9
+ module MCFDI
10
+ # Concepts Class
11
+ class Concept < Base
12
+ attr_accessor :code, :name, :measure_unit, :quantity, :price, :import
13
+
14
+ def initialize(args = {})
15
+ args.each { |key, value| send("#{key}=", value) }
16
+ end
17
+
18
+ def price=(price)
19
+ @price = format('%.2f', price).to_f
20
+ end
21
+
22
+ def import=(import)
23
+ @import = format('%.2f', import).to_f
24
+ end
25
+
26
+ # return original string of concept.
27
+ def original_string
28
+ [@quantity, @measure_unit, @code, @name, @price.to_f, @import]
29
+ end
30
+
31
+ # return hash with values for invoice xml.
32
+ def to_x
33
+ { cantidad: @quantity, unidad: @measure_unit, noIdentificacion: @code,
34
+ descripcion: @name, valorUnitario: @price, importe: @import }
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,43 @@
1
+ # business_name -> Razon Social
2
+ # fiscal_regime -> Regimen Fiscal
3
+ # address -> Domicilio Fiscal
4
+ # issued_in -> Expedido en
5
+
6
+ #
7
+ module MCFDI
8
+ # Entity Class for transmitter and receptor
9
+ class Entity < Base
10
+ attr_accessor :rfc, :business_name, :fiscal_regime, :address, :issued_in
11
+
12
+ def initialize(args = {})
13
+ args.each { |key, value| send("#{key}=", value) }
14
+ end
15
+
16
+ # if address is a hash, create a class of address with the hash.
17
+ def address=(data)
18
+ data = Address.new(data) unless data.is_a? Address
19
+ @address = data
20
+ end
21
+
22
+ # if address is a hash, create a class of address with the hash.
23
+ def issued_in=(address)
24
+ return unless address
25
+ data = Address.new(data) unless data.is_a? Address
26
+ @address = data
27
+ end
28
+
29
+
30
+ # return hash with values for invoice xml.
31
+ def to_x
32
+ { nombre: @business_name, rfc: @rfc }
33
+ end
34
+
35
+ # return original string without fiscal regime.
36
+ def original_string
37
+ issued = @issued_in ? @issued_in.original_string : nil
38
+ co = [@rfc, @business_name, @address.original_string]
39
+ co.insert(3, issued) if issued
40
+ co.flatten
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,304 @@
1
+ # created_at -> Fecha
2
+ # proof_type -> Tipo Comprobante
3
+ # payment_way -> Forma de Pago
4
+ # payment_conditions -> Condiciones de Pago
5
+ # exchange_rate -> Tipo de Cambio
6
+ # currency -> Moneda
7
+ # payment_method -> Metodo de Pago
8
+ # expedition_place -> Lugar de Expedicion
9
+ # transmitter -> Emisor
10
+ # receptor -> Receptor
11
+ # concepts -> Conceptos
12
+ # series -> Serie
13
+ # stamp -> Sello
14
+ # taxes -> Impuestos
15
+ # canceled -> Cancelada
16
+ # certificate_number -> noCertificado
17
+ # certificate -> Certificado
18
+ # complement -> Complemento
19
+ # payment_account_num -> numCtaPago
20
+ # addenda -> Addenda
21
+
22
+ #
23
+ module MCFDI
24
+ # Invoice Class the most important class.
25
+ class Invoice < Base
26
+ attr_accessor :version, :created_at, :proof_type, :payment_way,
27
+ :payment_conditions, :subtotal, :exchange_rate, :currency,
28
+ :total, :payment_method, :expedition_place, :transmitter,
29
+ :receptor, :concepts, :series, :folio, :stamp,
30
+ :taxes, :canceled, :certificate_number, :certificate,
31
+ :complement, :payment_account_num, :addenda
32
+
33
+ # default values.
34
+ @@defaults = {
35
+ tax_rate: 0.16, currency: 'pesos', version: '3.2', subtotal: 0.0,
36
+ exchange_rate: 1, concepts: [], taxes: Taxes.new, proof_type: 'ingreso',
37
+ total: 0.0
38
+ }
39
+
40
+ # to change default values.
41
+ def self.configure(options)
42
+ @@defaults = Invoice.rmerge(@@defaults, options)
43
+ @@defaults
44
+ end
45
+
46
+ def initialize(args = {})
47
+ args = @@defaults.merge(args)
48
+ args.each do |key, value|
49
+ method = "#{key}="
50
+ next unless self.respond_to? method
51
+ send(method, value)
52
+ end
53
+ end
54
+
55
+ def transmitter=(data)
56
+ data = Entity.new(data) unless data.is_a? Entity
57
+ @transmitter = data
58
+ end
59
+
60
+ def receptor=(data)
61
+ data = Entity.new(data) unless data.is_a? Entity
62
+ @receptor = data
63
+ end
64
+
65
+ def concepts=(data)
66
+ @concepts = []
67
+ if data.is_a? Array
68
+ data.map do |c|
69
+ c = Concept.new(c) unless c.is_a? Concept
70
+ @concepts << c
71
+ end
72
+ elsif data.is_a? Hash
73
+ @concepts << Concept.new(data)
74
+ elsif data.is_a? Concept
75
+ @concepts << data
76
+ end
77
+ @concepts
78
+ end
79
+
80
+ def created_at=(date)
81
+ date = date.strftime('%FT%R:%S') unless date.is_a? String
82
+ @created_at = date
83
+ end
84
+
85
+ def addenda=(addenda)
86
+ addenda = Addenda.new addenda unless addenda.is_a? Addenda
87
+ @addenda = addenda
88
+ end
89
+
90
+ # save xml to file and generate original string from schema.
91
+ def original_string_from_xslt
92
+ # fail 'You have to specify schema!' unless # TODO: create configuration.
93
+ save_xml
94
+ xml = "#{Rails.root}/#{@transmitter.rfc}-#{@series}-#{@folio}.xml"
95
+ sch = "#{Rails.root}/public/sat/schemas/cadenaoriginal_3_2.xslt"
96
+ @original_string_from_xslt ||= `xsltproc #{sch} #{xml}`
97
+ end
98
+
99
+ # Save invoice xml to file
100
+ def save_xml
101
+ file = File.new("#{@transmitter.rfc}-#{@series}-#{@folio}.xml", 'w+')
102
+ file.write(to_xml)
103
+ file.close
104
+ end
105
+
106
+ # Validate original string with the original string from schema
107
+ def validate_original_string
108
+ original_string == original_string_from_xslt
109
+ end
110
+
111
+ # return array of presented attributes.
112
+ # if any attribute does not have a value, will not be pushed to the array.
113
+ def attributes
114
+ a = [
115
+ @version, @created_at, @proof_type, @payment_way, @payment_conditions,
116
+ @subtotal.to_f, @exchange_rate, @currency, @total.to_f, @payment_method,
117
+ @expedition_place, @payment_account_num]
118
+ c = []
119
+ a.each do |v|
120
+ next unless v.present?
121
+ c << v
122
+ end
123
+ c
124
+ end
125
+
126
+ # Cadena Original
127
+ def original_string
128
+ params = []
129
+
130
+ attributes.each { |key| params << key }
131
+ params += @transmitter.original_string
132
+ params << @transmitter.fiscal_regime
133
+ params += @receptor.original_string
134
+
135
+ @concepts.each do |concept|
136
+ params += concept.original_string
137
+ end
138
+
139
+ if @taxes.transferred.any?
140
+ params += @taxes.transferred_original_string
141
+ params += [@taxes.total_transferred]
142
+ end
143
+
144
+ if @taxes.detained.any?
145
+ params += @taxes.detained_original_string
146
+ params += [@taxes.total_detained]
147
+ end
148
+
149
+ params.select(&:present?)
150
+ params.map! do |elem|
151
+ if elem.is_a? Float
152
+ elem = format('%.2f', elem)
153
+ else
154
+ elem = elem.to_s
155
+ end
156
+ elem
157
+ end
158
+
159
+ "||#{params.join('|')}||"
160
+ end # / Original_string
161
+
162
+ # return xml of the invoice.
163
+ def to_xml
164
+ ns = {
165
+ 'xmlns:cfdi' => 'http://www.sat.gob.mx/cfd/3',
166
+ 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
167
+ 'xsi:schemaLocation' => 'http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv32.xsd',
168
+ version: @version,
169
+ folio: @folio,
170
+ fecha: @created_at,
171
+ formaDePago: @payment_way,
172
+ subTotal: format('%.2f', @subtotal),
173
+ Moneda: @currency,
174
+ total: format('%.2f', @total),
175
+ metodoDePago: @payment_method,
176
+ tipoDeComprobante: @proof_type,
177
+ LugarExpedicion: @expedition_place
178
+ }
179
+ ns[:condicionesDePago] = @payment_conditions if
180
+ @payment_conditions.present?
181
+ ns[:serie] = @series if @series
182
+ ns[:TipoCambio] = @exchange_rate if @exchange_rate
183
+ ns[:NumCtaPago] = @payment_account_num if @NumCtaPago.present?
184
+
185
+ if @addenda
186
+ ns["xmlns:#{@addenda.name}"] = @addenda.namespace
187
+ ns['xsi:schemaLocation'] += (
188
+ ' ' + [@addenda.namespace, @addenda.xsd].join(' '))
189
+ end
190
+
191
+ if @certificate_number
192
+ ns[:noCertificado] = @certificate_number
193
+ ns[:certificado] = @certificate
194
+ end
195
+
196
+ ns[:sello] = @stamp if @stamp
197
+
198
+ @builder = Nokogiri::XML::Builder.new(encoding: 'UTF-8') do |xml|
199
+ xml.Comprobante(ns) do
200
+ ins = xml.doc.root.add_namespace_definition('cfdi', 'http://www.sat.gob.mx/cfd/3')
201
+ xml.doc.root.namespace = ins
202
+
203
+ xml.Emisor(@transmitter.to_x) do
204
+ xml.DomicilioFiscal(
205
+ @transmitter.address.to_x.reject { |_, v| !v.present? })
206
+ xml.ExpedidoEn(
207
+ @transmitter.issued_in.to_x.reject { |_, v| !v.present? }
208
+ ) if @transmitter.issued_in
209
+ xml.RegimenFiscal(Regimen: @transmitter.fiscal_regime)
210
+ end
211
+
212
+ xml.Receptor(@receptor.to_x) do
213
+ xml.Domicilio(@receptor.address.to_x.reject { |_, v| !v.present? })
214
+ end
215
+
216
+ xml.Conceptos do
217
+ @concepts.each do |concept|
218
+ concept_complement = nil
219
+
220
+ cc = concept.to_x.select { |_, v| v.present? }
221
+
222
+ cc = cc.map do |k, v|
223
+ v = format('%.2f', v) if v.is_a? Float
224
+ [k, v]
225
+ end.to_h
226
+
227
+ xml.Concepto(cc) { xml.ComplementoConcepto if concept_complement }
228
+ end
229
+ end
230
+
231
+ if @taxes.count > 0
232
+ tax_options = {}
233
+ total_trans = format('%.2f', @taxes.total_transferred)
234
+ total_detained = format('%.2f', @taxes.total_detained)
235
+ tax_options[:totalImpuestosTrasladados] = total_trans if
236
+ total_trans.to_i > 0
237
+ tax_options[:totalImpuestosRetenidos] = total_detained if
238
+ total_detained.to_i > 0
239
+ xml.Impuestos(tax_options) do
240
+ if @taxes.transferred.count > 0
241
+ xml.Traslados do
242
+ @taxes.transferred.each do |trans|
243
+ xml.Traslado(impuesto: trans.tax, tasa: format('%.2f', trans.rate),
244
+ importe: format('%.2f', trans.import))
245
+ end
246
+ end
247
+ end
248
+ if @taxes.detained.count > 0
249
+ xml.Retenciones do
250
+ @taxes.detained.each do |det|
251
+ xml.Retencion(impuesto: det.tax, tasa: format('%.2f', det.rate),
252
+ importe: format('%.2f', det.import))
253
+ end
254
+ end
255
+ end
256
+ end
257
+ end
258
+
259
+ xml.Complemento do
260
+ if @complemento
261
+ schema = 'http://www.sat.gob.mx/TimbreFiscalDigital '\
262
+ 'http://www.sat.gob.mx/TimbreFiscalDigital/'\
263
+ 'TimbreFiscalDigital.xsd'
264
+ ns_tfd = {
265
+ 'xsi:schemaLocation' => schema,
266
+ 'xmlns:tfd' => 'http://www.sat.gob.mx/TimbreFiscalDigital',
267
+ 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance'
268
+ }
269
+ xml['tfd'].TimbreFiscalDigital(@complemento.to_h.merge ns_tfd)
270
+ end
271
+ end
272
+
273
+ if @addenda
274
+ xml.Addenda do
275
+ @addenda.data.each do |k, v|
276
+ if v.is_a? Hash
277
+ xml[@addenda.nombre].send(k, v)
278
+ elsif v.is_a? Array
279
+ xml[@addenda.nombre].send(k, v)
280
+ else
281
+ xml[@addenda.nombre].send(k, v)
282
+ end
283
+ end
284
+ end
285
+ end
286
+ end
287
+ end
288
+ @builder.to_xml
289
+ end # to_xml
290
+
291
+ # validate generated xml with the schema
292
+ def validate_xml
293
+ errors = []
294
+ schema_file = "#{Rails.root}/public/sat/schemas/cfdv32.xsd"
295
+ xsd = Nokogiri::XML::Schema(File.read(schema_file))
296
+ doc = Nokogiri::XML(to_xml)
297
+
298
+ xsd.validate(doc).each do |error|
299
+ errors << error.message
300
+ end
301
+ errors
302
+ end # Validate_xml
303
+ end
304
+ end
data/lib/m_cfdi/key.rb ADDED
@@ -0,0 +1,19 @@
1
+ module MCFDI
2
+ require 'openssl'
3
+
4
+ # openssl pkcs8 -inform DER -in file.key -passin pass:password >> file.pem
5
+ class Key < OpenSSL::PKey::RSA
6
+ def initialize(file, password=nil)
7
+ if file.is_a? String
8
+ file = File.read(file)
9
+ end
10
+ super file, password
11
+ end
12
+
13
+ def seal(invoice)
14
+ original_string = invoice.original_string
15
+ invoice.stamp = Base64::encode64(
16
+ self.sign(OpenSSL::Digest::SHA1.new, original_string)).gsub(/\n/, '')
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,119 @@
1
+ # transferred -> Impuestos trasladado
2
+ # detained -> Impuestos retenidos
3
+ # tax -> Nombre del Impuesto
4
+ # rate -> Tasa
5
+ # import -> Importe
6
+
7
+ #
8
+ module MCFDI
9
+ class Taxes < Base
10
+ attr_accessor :transferred, :detained
11
+ def initialize
12
+ @transferred = []
13
+ @detained = []
14
+ end
15
+
16
+ # return total of all transferred taxes.
17
+ def total_transferred
18
+ return 0 unless @transferred.any?
19
+ @transferred.map(&:import).reduce(:+)
20
+ end
21
+
22
+ # return total of all detained taxes.
23
+ def total_detained
24
+ return 0 unless @detained.any?
25
+ @detained.map(&:import).reduce(:+)
26
+ end
27
+
28
+ # return count of all taxes.
29
+ def count
30
+ @transferred.count + @detained.count
31
+ end
32
+
33
+ def transferred=(tax)
34
+ if data.is_a? Array
35
+ data.map do |c|
36
+ c << Transferred.new(c) unless c.is_a? Tansferred
37
+ @transferred << c
38
+ end
39
+ elsif data.is_a? Hash
40
+ @transferred << Transferred.new(data)
41
+ elsif data.is_a? Transferred
42
+ @transferred << data
43
+ end
44
+ @transferred
45
+ end
46
+
47
+ def detained=(tax)
48
+ if data.is_a? Array
49
+ data.map do |c|
50
+ c << Detained.new(c) unless c.is_a? Detained
51
+ @detained << c
52
+ end
53
+ elsif data.is_a? Hash
54
+ @detained << Detained.new(data)
55
+ elsif data.is_a? Detained
56
+ @detained << data
57
+ end
58
+ @detained
59
+ end
60
+
61
+ # return original string of all transferred taxes.
62
+ def transferred_original_string
63
+ os = []
64
+ @transferred.each do |trans|
65
+ os += trans.original_string
66
+ end
67
+ os
68
+ end
69
+
70
+ # return original string of all detained taxes.
71
+ def detained_original_string
72
+ os = []
73
+ @taxes.detained.each do |detaind|
74
+ os += detaind.original_string
75
+ end
76
+ os
77
+ end
78
+ end
79
+
80
+ class Transferred
81
+ attr_accessor :tax, :rate, :import
82
+
83
+ def initialize(args = {})
84
+ args.each { |key, value| send("#{key}=", value) }
85
+ end
86
+
87
+ def rate=(rate)
88
+ @rate = format('%.2f', rate).to_f
89
+ end
90
+
91
+ def import=(import)
92
+ @import = format('%.2f', import).to_f
93
+ end
94
+
95
+ def original_string
96
+ [@tax, @rate, @import]
97
+ end
98
+ end
99
+
100
+ class Detained
101
+ attr_accessor :tax, :rate, :import
102
+
103
+ def initialize(args = {})
104
+ args.each { |key, value| send("#{key}=", value) }
105
+ end
106
+
107
+ def rate=(rate)
108
+ @rate = format('%.2f', rate).to_f
109
+ end
110
+
111
+ def import=(import)
112
+ @import = format('%.2f', import).to_f
113
+ end
114
+
115
+ def original_string
116
+ [@tax, @rate, @import]
117
+ end
118
+ end
119
+ end
@@ -0,0 +1,3 @@
1
+ module MCFDI
2
+ VERSION = "0.1.0"
3
+ end
data/lib/m_cfdi.rb ADDED
@@ -0,0 +1,15 @@
1
+ require "m_cfdi/version"
2
+ require "m_cfdi/base"
3
+ require "m_cfdi/addenda"
4
+ require "m_cfdi/address"
5
+ require "m_cfdi/certificate"
6
+ require "m_cfdi/complement"
7
+ require "m_cfdi/concept"
8
+ require "m_cfdi/entity"
9
+ require "m_cfdi/key"
10
+ require "m_cfdi/taxes"
11
+ require "m_cfdi/invoice"
12
+
13
+ module MCFDI
14
+ # Your code goes here...
15
+ end
data/m_cfdi.gemspec ADDED
@@ -0,0 +1,33 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'm_cfdi/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "m_cfdi"
8
+ spec.version = MCFDI::VERSION
9
+ spec.authors = ["Yaser Almasri"]
10
+ spec.email = ["info@masys.co"]
11
+
12
+ spec.summary = %q{CFDI Mexico.}
13
+ spec.description = %q{CFDI Mexico, To generate XML files from invoices of Mexico, Comprobantes Fiscales Digitales por Internet}
14
+ spec.homepage = "https://github.com/MaSys/cfdi"
15
+
16
+ # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
17
+ # delete this section to allow pushing this gem to any host.
18
+ if spec.respond_to?(:metadata)
19
+ spec.metadata['allowed_push_host'] = "https://rubygems.org"
20
+ else
21
+ raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
22
+ end
23
+
24
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
25
+ spec.bindir = "exe"
26
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
27
+ spec.require_paths = ["lib"]
28
+
29
+ spec.add_development_dependency "bundler", "~> 1.10"
30
+ spec.add_development_dependency "rake", "~> 10.0"
31
+ spec.add_development_dependency "rspec"
32
+ spec.add_development_dependency 'nokogiri', '~> 1.6'
33
+ end
metadata ADDED
@@ -0,0 +1,125 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: m_cfdi
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Yaser Almasri
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2015-12-04 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.10'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.10'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: nokogiri
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '1.6'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '1.6'
69
+ description: CFDI Mexico, To generate XML files from invoices of Mexico, Comprobantes
70
+ Fiscales Digitales por Internet
71
+ email:
72
+ - info@masys.co
73
+ executables: []
74
+ extensions: []
75
+ extra_rdoc_files: []
76
+ files:
77
+ - ".gitignore"
78
+ - ".rspec"
79
+ - ".travis.yml"
80
+ - CODE_OF_CONDUCT.md
81
+ - Gemfile
82
+ - LICENSE
83
+ - README.md
84
+ - Rakefile
85
+ - bin/console
86
+ - bin/setup
87
+ - lib/m_cfdi.rb
88
+ - lib/m_cfdi/addenda.rb
89
+ - lib/m_cfdi/address.rb
90
+ - lib/m_cfdi/base.rb
91
+ - lib/m_cfdi/certificate.rb
92
+ - lib/m_cfdi/complement.rb
93
+ - lib/m_cfdi/concept.rb
94
+ - lib/m_cfdi/entity.rb
95
+ - lib/m_cfdi/invoice.rb
96
+ - lib/m_cfdi/key.rb
97
+ - lib/m_cfdi/taxes.rb
98
+ - lib/m_cfdi/version.rb
99
+ - m_cfdi.gemspec
100
+ homepage: https://github.com/MaSys/cfdi
101
+ licenses: []
102
+ metadata:
103
+ allowed_push_host: https://rubygems.org
104
+ post_install_message:
105
+ rdoc_options: []
106
+ require_paths:
107
+ - lib
108
+ required_ruby_version: !ruby/object:Gem::Requirement
109
+ requirements:
110
+ - - ">="
111
+ - !ruby/object:Gem::Version
112
+ version: '0'
113
+ required_rubygems_version: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ requirements: []
119
+ rubyforge_project:
120
+ rubygems_version: 2.4.5.1
121
+ signing_key:
122
+ specification_version: 4
123
+ summary: CFDI Mexico.
124
+ test_files: []
125
+ has_rdoc: