Class: Facturama::Samples::SampleApiWeb

Inherits:
SampleApi
  • Object
show all
Defined in:
lib/samples/sample_api_web.rb

Instance Method Summary collapse

Constructor Details

#initializeSampleApiWeb

Returns a new instance of SampleApiWeb.



14
15
16
# File 'lib/samples/sample_api_web.rb', line 14

def initialize

end

Instance Method Details

#add_items_to_cfdi(facturama, currency, cfdi) ⇒ Object



371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
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
# File 'lib/samples/sample_api_web.rb', line 371

def add_items_to_cfdi(facturama, currency, cfdi)

    lst_products = facturama.products.list
    lst_products_size = lst_products.length

    n_items = (rand( lst_products.length ) % 10) + 1

    decimals = currency['Decimals'].to_i

    # Lista de conceptos para el CFDI
    lst_items = Array.new


    n_begin = lst_products_size - 1 - n_items

    for index in n_begin..lst_products_size

        product = lst_products[index]        # Un producto cualquiera

        if( product.nil? )
            break

        end

        quantity = rand(5) + 1          # una cantidad aleatoria de elementos de este producto

        discount = product['Price'] % ( product['Price']) == 0 ? 1 : rand( (product['Price'].to_i ) )
        subtotal = ( product['Price'] * quantity).round(decimals)    # Redondeo de acuerdo a la moneda



        item = Facturama::Models::Item.new({
                                               ProductCode: product['CodeProdServ'],
                                               UnitCode: product['UnitCode'],
                                               Unit: product['Unit'],
                                               Description: product['Description'],
                                               IdentificationNumber: product['IdentificationNumber'],
                                               Quantity: quantity,
                                               Discount: discount.round(decimals),
                                               UnitPrice: product['Price'].round(decimals),
                                               Subtotal: subtotal,
                                               Taxes: nil

                                           })


        base_amount = (subtotal - discount).round(decimals)
        taxes = product['Taxes'].map { |t|
            Facturama::Models::Tax.new(
                Name: t['Name'],
                IsQuota: t['IsQuota'],
                IsRetention: t['IsRetention'],
                Rate: t['Rate'].to_f.round(decimals),
                Base: base_amount,
                Total: (base_amount * t['Rate'].to_f).round(decimals)
            )
        }

        retentions_amount = 0
        transfers_amount = 0
        if taxes.length > 0
            item.Taxes = taxes
            # Calculo del monto total del concepto, tomando en cuenta los impuestos
            retentions_amount = item.Taxes.select { |tax| tax.IsRetention  }.sum(&:Total)
            transfers_amount = item.Taxes.select { |tax| ! tax.IsRetention  }.sum(&:Total)

        end

        item.Total = (item.Subtotal - item.Discount  + transfers_amount - retentions_amount).round(decimals)

        lst_items.push(item)

    end

    cfdi.Items = lst_items

end

#create_api_instanceObject


CONFIGURACION DEL ENTORNO DE LA API



70
71
72
73
74
75
76
77
78
# File 'lib/samples/sample_api_web.rb', line 70

def create_api_instance
    facturama_user='pruebas'
    facturama_password='pruebas2011'
    is_development = true             # true = Modo de pruebas / sandbox,   false = Modo de Producción (Timbrado real)


    #Creacion de una instancia de FacturamaApi
    Facturama::FacturamaApiWeb.new(facturama_user,facturama_password,is_development)
end

#runObject



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
# File 'lib/samples/sample_api_web.rb', line 18

def run




            puts "============================================================"
            puts "                    FACTURAMA WEB SDK   #{Facturama::VERSION}"
            puts "============================================================"


            # Creación de una instacia de la API Facturama, configurado con los datos del usuario de pruebas
            facturama = create_api_instance


            # Invocaciones a los ejemplos de uso de los servicios de Facturama API
            begin
                #sample_clients(facturama)          # Servicio de cliente

                sample_products(facturama)          # Servicio de productos

                #sample_cfdis(facturama)              # Servicio de CFDI





            rescue FacturamaException => ex
                puts "----------- EXCEPCIONES -----------"
                puts " * " + ex.message

                if ex.details
                    ex.details.each do |item|
                        puts "#{item[0]}: " + item[1].join(",")
                    end
                end





            rescue Exception => ex
                puts "----------- EXCEPCIONES -----------"
                puts " * " + ex.to_s
            end
end

#sample_cfdis(facturama) ⇒ Object


EJEMPLO DEL SERVICIO DE CFDI En la API WEB el emisor es Siempre la entidad fiscal configurada en la cuenta



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
# File 'lib/samples/sample_api_web.rb', line 277

def sample_cfdis( facturama )
    puts "===== Ejemplo de CFDI - Inicio ====="

    # Se obtiene la moneda con el valor "MXN"
    lst_currencies = facturama::catalog.currencies
    currency = lst_currencies.select {|currency| currency["Value"] == "MXN" }.first


    # Creacion del cfdi en su forma general (sin items / productos) asociados
    cfdi_model = sample_cfdis_create(facturama, currency)

    # Agregar los items que lleva el cfdi ( para este ejemplo, se agregan con datos aleatorios)
    add_items_to_cfdi(facturama, currency, cfdi_model)

    # Creación del CFDI mediante la API, para su creación
    cfdi = facturama.cfdis.create(cfdi_model)
    cfdi_uuid = cfdi['Complement']['TaxStamp']['Uuid']
    puts "Se creó exitosamente el cfdi con el folio fiscal:  " + cfdi_uuid

    # Descarga de los arvhivos PDF y XML del cfdi recien creado
    file_path = "factura" + cfdi_uuid
    facturama.cfdis.save_pdf( file_path + ".pdf",  cfdi['Id'])
    facturama.cfdis.save_xml( file_path + ".xml",  cfdi['Id'])

    # Envio del cfdi por correo
    if facturama.cfdis.send_by_mail(cfdi['Id'], "[email protected]", "Factura del servicio" )
        puts "Se envió por correo exitosamente el cfdi con el folio fiscal: " + cfdi_uuid
    end

    # Se elmina el cfdi recien creado
    facturama.cfdis.remove(cfdi['Id'])
    puts "Se elminó exitosamente el cfdi con el folio fiscal: " + cfdi_uuid


    # Consulta de cfdi por palabra clave o Rfc
    lst_by_rfc = facturama.cfdis.list_by_rfc("ESO1202108R2")
    lst_by_keyword = facturama.cfdis.list_by_keyword("Software")

    puts "Se obtiene la lista de facturas por RFC: #{lst_by_rfc.length}"
    puts "Se obtiene la lista de facturas por KEYWORD: #{lst_by_keyword.length}"



    puts "===== Ejemplo de CFDI - Fin ====="
end

#sample_cfdis_create(facturama, currency) ⇒ 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
# File 'lib/samples/sample_api_web.rb', line 325

def sample_cfdis_create(facturama, currency)

    # Nombre para el CFDI, para el ejemplo, tomado el primero de la lista del catálogo de nombres en el PDF
    name_for_pdf = facturama.catalog.name_ids.first; # Nombre en el pdf: "Factura"

    # Método de pago
    payment_method = facturama.catalog.payment_methods.select {|method| method["Name"] == "Pago en una sola exhibición" }.first


    # Forma de pago
    payment_form = facturama.catalog.payment_forms.select {|method| method["Name"] == "Efectivo" }.first


    # Cliente (se toma como cliente el "cliente generico", aquel que tiene el RFC genérico),
    #(como los clientes son exclusivos para cada usuario, se debe previamente dar de alta este cliente)
    client = facturama.clients.list.select {|client| client["Rfc"] == "XAXX010101000" }.first


    # Lugar de expedición
    branch_office = facturama.branch_office.list.first

    # Fecha de emision (ahora mismo)
    date = Time.now.strftime("%Y-%m-%d %H:%M:%S")

    cfdi = Facturama::Models::Cfdi.new(
        {
            NameId: name_for_pdf['Value'],
            CfdiType: Facturama::CfdiType::INGRESO,
            PaymentForm: payment_form['Value'],
            PaymentMethod: payment_method['Value'],
            Currency: currency['Value'],
            Date: date,
            ExpeditionPlace: branch_office['Address']['ZipCode'],
            Receiver: {
                CfdiUse: client['CfdiUse'],
                Name: client['Name'],
                Rfc: client['Rfc']
            },
            Items: []
        }
    )


end

#sample_clients(facturama) ⇒ Object

EJEMPLO DEL SERVICIO DE CLIENTES

  • Listado de clientes

  • Agregar cliente

  • Obtener cliente específico y editarlo



88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/samples/sample_api_web.rb', line 88

def sample_clients(facturama)

    sample_clients_list(facturama)    # Listar todos los clientes

    new_client = sample_clients_create(facturama)  # Agregar cliente
    client_id = new_client['Id']                    # Id del cliente recientemente agregado

    sample_clients_retrieve_and_update(facturama, client_id)

    sample_clients_remove(facturama, client_id)

end

#sample_clients_create(facturama) ⇒ Object

Agrega un cliente



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/samples/sample_api_web.rb', line 120

def sample_clients_create(facturama)
    puts "===== Agregar cliente - Inicio ====="

    facturama.clients.create(Facturama::Models::Client.new(
        {   Email: "[email protected]",
            Rfc: "RODJ899315654",
            CfdiUse: "P01",
            Name: "Pedro Perez Development Environment",

            Address: {Country: "MEXICO",
                      ExteriorNumber: "1230",
                      InteriorNumber: "B",
                      Locality: "San Luis",
                      Municipality: "San Luis Potosí",
                      Neighborhood: "Lomas 4ta",
                      State: "San Luis Potosí",
                      Street: "Cañada de Gomez",
                      ZipCode: "78220"
            }
        }))

    puts "===== Agregar cliente - Fin ====="
end

#sample_clients_list(facturama) ⇒ Object

Obtiene el listado de clientes y muestra la cantidad de los mismos



104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/samples/sample_api_web.rb', line 104

def sample_clients_list(facturama)
    puts "===== Obtener los clientes - Inicio ====="

    lst_clients = facturama.clients.list      # Se obtiene una lista con todos los clientes
    lst_clients_count = lst_clients.count         # Cantidad inicial de clientes



    puts "Cantidad inicial de clientes: " + lst_clients_count.to_s

    puts "===== Obtener los clientes - Fin ====="
end

#sample_clients_remove(facturama, client_id) ⇒ Object

Elimina un cliente



184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/samples/sample_api_web.rb', line 184

def sample_clients_remove(facturama, client_id)

    puts "===== Eliminar cliente - Inicio ====="

    specific_client = facturama.clients.remove(client_id)

    puts "Cliente eliminado: "
    puts JSON[specific_client]

    puts "===== Eliminar cliente - Fin ====="

end

#sample_clients_retrieve_and_update(facturama, client_id) ⇒ Object

Obtiene un cliente específico, lo edita y lo guarda



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
# File 'lib/samples/sample_api_web.rb', line 147

def sample_clients_retrieve_and_update(facturama, client_id)

    puts "===== Obtener cliente y editarlo - Inicio ====="

    # Se obtiene el cliente con el Id especificado
    specific_client = facturama.clients.retrieve(client_id)


    # Se ha encontrado un cliente con ese Id
    if specific_client != nil then

        puts "Specific Client: "
        puts JSON[specific_client]

        # Edición del campo RFC
        specific_client['Rfc'] = "XAXX010101000"
        specific_client['Email'] = "[email protected]"
        facturama.clients.update(specific_client, client_id)


        # Se obtiene nuevamente el cliente para confirmar que ha cambiado
        specific_client = facturama.clients.retrieve(client_id)

        if specific_client['Rfc'] == "XAXX010101000" then
            puts "Cliente editado, ahora su RFC es XAXX010101000"
        else
            puts "Error al editar cliente"
        end
    end


    puts "===== Obtener cliente y editarlo - Fin ====="
end

#sample_products(facturama) ⇒ Object


EJEMPLO DEL SERVICIO DE PRODUCTOS



203
204
205
206
207
# File 'lib/samples/sample_api_web.rb', line 203

def sample_products( facturama )
    sample_products_list(facturama)         # Listar todos los productos

    sample_products_create(facturama)       # Agregar producto y eliminarlo
end

#sample_products_create(facturama) ⇒ Object

Agrega un cliente



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
# File 'lib/samples/sample_api_web.rb', line 226

def sample_products_create(facturama)
    puts "===== Agregar producto - Inicio ====="

    unit = facturama.catalog.units("servicio").first                        # La primera unidad que tenga que ver con servicio
    prod = facturama.catalog.products_or_services("desarrollo").first       # Se toma el primer producto o servicio



    product_model = Facturama::Models::Product.new(
        {
            Unit: "Servicio",
            UnitCode: unit['Value'],
            IdentificationNumber: "WEB003",
            Name: "Sitio Web CMS",
            Description: "Desarrollo e implementación de sitio web empleando un CMS",
            Price: 6500.0,
            CodeProdServ: prod['Value'],
            CuentaPredial: "123",

            Taxes: [
                {
                    Name: "IVA",
                    Rate: 0.16,
                    IsRetention: false
                }
            ]
        }
    )

    product = facturama.products.create(product_model)

    puts "Se creo exitosamente un producto con el id: " + product['Id']


    facturama.products.delete( product['Id'] )
    puts "Se eliminó exitosamente un producto con el id: " + product['Id']


    puts "===== Agregar producto - Fin ====="
end

#sample_products_list(facturama) ⇒ Object

Obtiene el listado de productos y muestra la cantidad de los mismos



212
213
214
215
216
217
218
219
220
221
# File 'lib/samples/sample_api_web.rb', line 212

def sample_products_list(facturama)
    puts "===== Obtener los productos - Inicio ====="

    lst_products = facturama.products.list       # Se obtiene una lista con todos los productos
    lst_products_count = lst_products.count       # Cantidad inicial de productos

    puts "Cantidad inicial de productos: " + lst_products_count.to_s

    puts "===== Obtener los productos - Fin ====="
end