spree_zaez_cielo 3.0.0 → 3.0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (79) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +14 -0
  3. data/.rspec +1 -0
  4. data/.travis.yml +12 -0
  5. data/Gemfile +7 -0
  6. data/Guardfile +90 -0
  7. data/LICENSE +26 -0
  8. data/README.md +71 -0
  9. data/Rakefile +21 -0
  10. data/app/assets/images/credit_cards/icons/amex.png +0 -0
  11. data/app/assets/images/credit_cards/icons/diners.png +0 -0
  12. data/app/assets/images/credit_cards/icons/elo.png +0 -0
  13. data/app/assets/images/credit_cards/icons/jcb.png +0 -0
  14. data/app/assets/javascripts/spree/backend/spree_zaez_cielo.js +2 -0
  15. data/app/assets/javascripts/spree/frontend/app/cielo/cielo_credit.js.coffee +107 -0
  16. data/app/assets/javascripts/spree/frontend/app/cielo/cielo_debt.js.coffee +123 -0
  17. data/app/assets/javascripts/spree/frontend/spree_zaez_cielo.js +2 -0
  18. data/app/assets/stylesheets/spree/backend/spree_zaez_cielo.css +4 -0
  19. data/app/assets/stylesheets/spree/frontend/spree_zaez_cielo.css +4 -0
  20. data/app/controllers/spree/admin/cielo_settings_controller.rb +38 -0
  21. data/app/controllers/spree/api/orders_controller_decorator.rb +57 -0
  22. data/app/controllers/spree/cielo_debt_controller.rb +66 -0
  23. data/app/helpers/spree/frontend_helper_decorator.rb +18 -0
  24. data/app/models/spree/payment/gateway_options_decorator.rb +14 -0
  25. data/app/models/spree/payment_method/cielo_credit.rb +270 -0
  26. data/app/models/spree/payment_method/cielo_debt.rb +182 -0
  27. data/app/overrides/spree/admin/shared/sub_menu/_configuration/add_cielo_settings_to_configuration_tab.html.erb.deface +2 -0
  28. data/app/overrides/spree/checkout/_payment/add_container_portions_to_existing_cards.html.erb.deface +4 -0
  29. data/app/overrides/spree/checkout/edit/add_container_error_to_checkout_page.html.erb.deface +3 -0
  30. data/app/overrides/spree/payments/_payment/add_portions_to_payment_show.html.erb.deface +5 -0
  31. data/app/views/spree/admin/cielo_settings/edit.html.erb +123 -0
  32. data/app/views/spree/admin/payments/source_forms/_cielocredit.html.erb +38 -0
  33. data/app/views/spree/admin/payments/source_forms/_cielodebt.html.erb +40 -0
  34. data/app/views/spree/admin/payments/source_views/_cielocredit.html.erb +33 -0
  35. data/app/views/spree/admin/payments/source_views/_cielodebt.html.erb +33 -0
  36. data/app/views/spree/api/errors/unavailable_credit_card.v1.rabl +2 -0
  37. data/app/views/spree/api/orders/portions.html.erb +14 -0
  38. data/app/views/spree/checkout/payment/_cielocredit.html.erb +38 -0
  39. data/app/views/spree/checkout/payment/_cielodebt.html.erb +40 -0
  40. data/bin/rails +7 -0
  41. data/config/locales/en.yml +62 -0
  42. data/config/locales/pt-br.yml +62 -0
  43. data/config/routes.rb +12 -0
  44. data/db/migrate/20150716190648_add_portions_to_spree_payments.rb +5 -0
  45. data/lib/generators/spree_zaez_cielo/install/install_generator.rb +31 -0
  46. data/lib/spree/cielo_configuration.rb +72 -0
  47. data/lib/spree_zaez_cielo/engine.rb +38 -0
  48. data/lib/spree_zaez_cielo/factories.rb +49 -0
  49. data/lib/spree_zaez_cielo.rb +5 -0
  50. data/spec/controllers/spree/api/orders_controller_decorator_spec.rb +89 -0
  51. data/spec/features/admin/cielo_credit_actions_spec.rb +12 -0
  52. data/spec/features/admin/cielo_debt_actions_spec.rb +12 -0
  53. data/spec/features/admin/cielo_settings_spec.rb +111 -0
  54. data/spec/features/checkout_with_cielo_credit_spec.rb +68 -0
  55. data/spec/features/checkout_with_cielo_debt_spec.rb +77 -0
  56. data/spec/fixtures/cielo_returns/authorize_error.json +1 -0
  57. data/spec/fixtures/cielo_returns/authorize_success.json +1 -0
  58. data/spec/fixtures/cielo_returns/capture_error.json +1 -0
  59. data/spec/fixtures/cielo_returns/capture_success.json +1 -0
  60. data/spec/fixtures/cielo_returns/create_error.json +1 -0
  61. data/spec/fixtures/cielo_returns/create_success.json +1 -0
  62. data/spec/fixtures/cielo_returns/error_001.json +1 -0
  63. data/spec/fixtures/cielo_returns/purchase_success.json +1 -0
  64. data/spec/fixtures/cielo_returns/token_success.json +1 -0
  65. data/spec/fixtures/cielo_returns/void_error.json +1 -0
  66. data/spec/fixtures/cielo_returns/void_success.json +1 -0
  67. data/spec/lib/spree/cielo_configuration_spec.rb +73 -0
  68. data/spec/models/spree/payment/gateway_options_decorator_spec.rb +51 -0
  69. data/spec/models/spree/payment_method/cielo_credit_spec.rb +233 -0
  70. data/spec/models/spree/payment_method/cielo_debt_spec.rb +166 -0
  71. data/spec/spec_helper.rb +89 -0
  72. data/spec/support/capybara_login.rb +13 -0
  73. data/spec/support/checkout_helpers.rb +75 -0
  74. data/spec/support/controller_hacks.rb +20 -0
  75. data/spec/support/shared_contexts/checkout_setup.rb +9 -0
  76. data/spec/support/shared_examples/admin_cielo_actions.rb +57 -0
  77. data/spree_zaez_cielo.gemspec +38 -0
  78. data/vendor/assets/javascripts/jquery.payment.js +598 -0
  79. metadata +107 -3
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 51ef11f1d6973a4eba61d4171694b1c9a8735a7a
4
- data.tar.gz: c73ccdf477ac985d3e6535f5b1193e146b590622
3
+ metadata.gz: 5205fe1317b2ce0f3a1ac8df058c5bd6e4221954
4
+ data.tar.gz: 1581e9ba04a5c0c3c507c0fec3b843496f353add
5
5
  SHA512:
6
- metadata.gz: 2f370d259d924b90793ed026aa63c693b52ca1ab5c42cb74706c7e2aae162c15aca8736e95ed72ff3e5ef497ed81b0ed19cc076fa7cf1e6a36bfcefca660c503
7
- data.tar.gz: 9d78bb6376419da0f542649c2e9f7de347eaca69f547e34f1c7307ab1c6a6516c11b8248ee95a51eae11da8b6e1e52f71de29d13192c1abab252d453522b3eab
6
+ metadata.gz: 1162e57ac25eb503d78ab47325b937f31eed2d6ad2e2eb020004e7cb01e3b1b582911080c406c723b4d4d917c94047c2d680f01b94105aedefffe3726e95e432
7
+ data.tar.gz: de3acfbdb0835ac69b99257cbf266bcc93a91391f44b73d3f8680b8cebb68763b71e74dcfd49d5e9f6f560c7ef0d27ebf2d668e053eabd7875fdc6cdfa905ee7
data/.gitignore ADDED
@@ -0,0 +1,14 @@
1
+ \#*
2
+ *~
3
+ .#*
4
+ .DS_Store
5
+ .idea
6
+ .project
7
+ .sass-cache
8
+ coverage
9
+ Gemfile.lock
10
+ tmp
11
+ nbproject
12
+ pkg
13
+ *.swp
14
+ spec/dummy
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --format documentation --color
data/.travis.yml ADDED
@@ -0,0 +1,12 @@
1
+ before_script:
2
+ - sh -e /etc/init.d/xvfb start
3
+ - export DISPLAY=:99.0
4
+ bundler_args: --quiet
5
+ script:
6
+ - bundle exec rake test_app
7
+ - bundle exec rspec
8
+ language: ruby
9
+ rvm:
10
+ - 2.0.0
11
+ - 2.1.2
12
+ - 2.1.5
data/Gemfile ADDED
@@ -0,0 +1,7 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gem 'spree', github: 'spree/spree', branch: '3-0-stable'
4
+ # Provides basic authentication functionality for testing parts of your engine
5
+ gem 'spree_auth_devise', github: 'spree/spree_auth_devise', branch: '3-0-stable'
6
+
7
+ gemspec
data/Guardfile ADDED
@@ -0,0 +1,90 @@
1
+ # A sample Guardfile
2
+ # More info at https://github.com/guard/guard#readme
3
+
4
+ ## Uncomment and set this to only include directories you want to watch
5
+ # directories %w(app lib config test spec feature)
6
+
7
+ ## Uncomment to clear the screen before every task
8
+ # clearing :on
9
+
10
+ ## Guard internally checks for changes in the Guardfile and exits.
11
+ ## If you want Guard to automatically start up again, run guard in a
12
+ ## shell loop, e.g.:
13
+ ##
14
+ ## $ while bundle exec guard; do echo "Restarting Guard..."; done
15
+ ##
16
+ ## Note: if you are using the `directories` clause above and you are not
17
+ ## watching the project directory ('.'), the you will want to move the Guardfile
18
+ ## to a watched dir and symlink it back, e.g.
19
+ #
20
+ # $ mkdir config
21
+ # $ mv Guardfile config/
22
+ # $ ln -s config/Guardfile .
23
+ #
24
+ # and, you'll have to watch "config/Guardfile" instead of "Guardfile"
25
+
26
+ # Note: The cmd option is now required due to the increasing number of ways
27
+ # rspec may be run, below are examples of the most common uses.
28
+ # * bundler: 'bundle exec rspec'
29
+ # * bundler binstubs: 'bin/rspec'
30
+ # * spring: 'bin/rspec' (This will use spring if running and you have
31
+ # installed the spring binstubs per the docs)
32
+ # * zeus: 'zeus rspec' (requires the server to be started separately)
33
+ # * 'just' rspec: 'rspec'
34
+
35
+ guard :shell do
36
+ watch(/^db\/migrate\/.*\.rb/) do |m|
37
+ puts "#{m[0]} Changed"
38
+ `bundle exec rake test_app`
39
+ end
40
+ end
41
+
42
+ guard :bundler do
43
+ watch('Gemfile')
44
+ # Uncomment next line if Gemfile contain `gemspec' command
45
+ watch(/^.+\.gemspec/)
46
+ end
47
+
48
+ guard :rspec, cmd: "bundle exec rspec" do
49
+ require "guard/rspec/dsl"
50
+ dsl = Guard::RSpec::Dsl.new(self)
51
+
52
+ # Feel free to open issues for suggestions and improvements
53
+
54
+ # RSpec files
55
+ rspec = dsl.rspec
56
+ watch(rspec.spec_helper) { rspec.spec_dir }
57
+ watch(rspec.spec_support) { rspec.spec_dir }
58
+ watch(rspec.spec_files)
59
+
60
+ # Ruby files
61
+ ruby = dsl.ruby
62
+ dsl.watch_spec_files_for(ruby.lib_files)
63
+
64
+ # Rails files
65
+ rails = dsl.rails(view_extensions: %w(erb haml slim))
66
+ dsl.watch_spec_files_for(rails.app_files)
67
+ dsl.watch_spec_files_for(rails.views)
68
+
69
+ watch(rails.controllers) do |m|
70
+ [
71
+ rspec.spec.("routing/#{m[1]}_routing"),
72
+ rspec.spec.("controllers/#{m[1]}_controller"),
73
+ rspec.spec.("acceptance/#{m[1]}")
74
+ ]
75
+ end
76
+
77
+ # Rails config changes
78
+ watch(rails.spec_helper) { rspec.spec_dir }
79
+ watch(rails.routes) { "#{rspec.spec_dir}/routing" }
80
+ watch(rails.app_controller) { "#{rspec.spec_dir}/controllers" }
81
+
82
+ # Capybara features specs
83
+ watch(rails.view_dirs) { |m| rspec.spec.("features/#{m[1]}") }
84
+
85
+ # Turnip features and steps
86
+ watch(%r{^spec/acceptance/(.+)\.feature$})
87
+ watch(%r{^spec/acceptance/steps/(.+)_steps\.rb$}) do |m|
88
+ Dir[File.join("**/#{m[1]}.feature")][0] || "spec/acceptance"
89
+ end
90
+ end
data/LICENSE ADDED
@@ -0,0 +1,26 @@
1
+ Copyright (c) 2015 Zaez Inovação Digital
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without modification,
5
+ are permitted provided that the following conditions are met:
6
+
7
+ * Redistributions of source code must retain the above copyright notice,
8
+ this list of conditions and the following disclaimer.
9
+ * Redistributions in binary form must reproduce the above copyright notice,
10
+ this list of conditions and the following disclaimer in the documentation
11
+ and/or other materials provided with the distribution.
12
+ * Neither the name Spree nor the names of its contributors may be used to
13
+ endorse or promote products derived from this software without specific
14
+ prior written permission.
15
+
16
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
20
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
data/README.md ADDED
@@ -0,0 +1,71 @@
1
+ Spree Cielo [![Build Status](https://travis-ci.org/zaeznet/spree_zaez_cielo.svg?branch=master)](https://travis-ci.org/zaeznet/spree_zaez_cielo)
2
+ ==============
3
+
4
+ This gem implements some funcionalities of Cielo to Spree Commerce.
5
+
6
+ Installation
7
+ ------------
8
+
9
+ Add spree_zaez_cielo to your Gemfile:
10
+
11
+ ```ruby
12
+ gem 'spree_zaez_cielo', github: 'zaeznet/spree_zaez_cielo'
13
+ ```
14
+
15
+ Bundle your dependencies and run the installation generator:
16
+
17
+ ```shell
18
+ bundle
19
+ bundle exec rails g spree_zaez_cielo:install
20
+ ```
21
+
22
+ Settings
23
+ -------
24
+
25
+ To configure the Cielo settings, go to /admin/cielo_settings/edit (or access by the menu in configurations > Cielo Settings).
26
+ To set the settings through a config file, you can assign values to the settings like so:
27
+
28
+ ```ruby
29
+ Spree::CieloConfig[:token] = 'asd-123'
30
+ ```
31
+
32
+ See all settings in /lib/spree/cielo_configuration.rb.
33
+
34
+ Funcionalities
35
+ -------
36
+
37
+ This gem supports credit and debt transactions. The credit card available are:
38
+
39
+ * Visa;
40
+ * Mastercard;
41
+ * Diners;
42
+ * Discover;
43
+ * Elo;
44
+ * American Express;
45
+ * JCB.
46
+
47
+ And the debt cards are:
48
+
49
+ * Visa;
50
+ * Mastercard.
51
+
52
+ The transaction by token can be set by setting (using the `Spree::CieloConfig[:generate_token]`).
53
+
54
+ Testing
55
+ -------
56
+
57
+ First bundle your dependencies, then run `rake`. `rake` will default to building the dummy app if it does not exist, then it will run specs. The dummy app can be regenerated by using `rake test_app`.
58
+
59
+ ```shell
60
+ bundle
61
+ bundle exec rake
62
+ ```
63
+
64
+ When testing your applications integration with this extension you may use it's factories.
65
+ Simply add this require statement to your spec_helper:
66
+
67
+ ```ruby
68
+ require 'spree_zaez_cielo/factories'
69
+ ```
70
+
71
+ Copyright (c) 2015 Zaez Inovação Digital, released under the New BSD License
data/Rakefile ADDED
@@ -0,0 +1,21 @@
1
+ require 'bundler'
2
+ Bundler::GemHelper.install_tasks
3
+
4
+ require 'rspec/core/rake_task'
5
+ require 'spree/testing_support/extension_rake'
6
+
7
+ RSpec::Core::RakeTask.new
8
+
9
+ task :default do
10
+ if Dir["spec/dummy"].empty?
11
+ Rake::Task[:test_app].invoke
12
+ Dir.chdir("../../")
13
+ end
14
+ Rake::Task[:spec].invoke
15
+ end
16
+
17
+ desc 'Generates a dummy app for testing'
18
+ task :test_app do
19
+ ENV['LIB_NAME'] = 'spree_zaez_cielo'
20
+ Rake::Task['extension:test_app'].invoke
21
+ end
@@ -0,0 +1,2 @@
1
+ //= require ../frontend/app/cielo/cielo_credit
2
+ //= require ../frontend/app/cielo/cielo_debt
@@ -0,0 +1,107 @@
1
+ #= require_self
2
+ class window.CieloCredit
3
+ afterConstructor: ->
4
+
5
+ beforeConstructor: ->
6
+
7
+ constructor: (@credit_info, defaultExecution = true) ->
8
+ do @beforeConstructor
9
+ do @defaultExecution if defaultExecution
10
+ do @afterConstructor
11
+
12
+ defaultExecution: ->
13
+ do @setRoutes
14
+ do @setListeners
15
+ do @setExistingOrNewCard
16
+
17
+ getCreditInfo: ->
18
+ @credit_info
19
+
20
+ # Faz uma requisicao para pegar as parcelas disponiveis
21
+ # para o tipo de bandeira digitada
22
+ setCreditCard: ->
23
+ $('#cielo_unrecognized').hide()
24
+ type = $.payment.cardType($('#cielo_card_number').val())
25
+ $('#cielo_credit_cc_type').val(type)
26
+ if $('#cielo_card_number').val().length > 12
27
+ if type == null
28
+ $('#cielo_unrecognized').show()
29
+ $('#cielo_portion').html('')
30
+ else
31
+ type = 'master' if type == 'mastercard'
32
+ type = 'diners' if type == 'dinersclub'
33
+ params =
34
+ cc_type: type
35
+ $.ajax
36
+ url: Spree.routes.portions(Spree.current_order_id)
37
+ data: params
38
+ dataType: 'html'
39
+ success: (ret) ->
40
+ $('#cielo_portion').html(ret)
41
+ $('input[type="radio"][name="portions"]').click => setPortionsValue('')
42
+ error: (xhr) ->
43
+ $('#cielo_portion').html(xhr.responseText)
44
+
45
+ # Esconde as parcelas quando a opcao de cartao existente nao esta habilitada
46
+ setExistingOrNewCard: ->
47
+ if ($ '#existing_cards').is('*')
48
+ ($ '#use_existing_card_yes').click ->
49
+ ($ '#portions_existing_cards').show()
50
+ # verifica se alguma parcela dos cartoes existentes esta checada
51
+ # se sim, seta ela no input onde o valor e armazenado
52
+ checked_portion = $("input[type='radio'][name='existing_card_portions']:checked").val()
53
+ if parseInt(checked_portion) > 0
54
+ $('#payment_portions').val(checked_portion)
55
+ else
56
+ $('#payment_portions').val('1')
57
+ ($ '#use_existing_card_no').click ->
58
+ ($ '#portions_existing_cards').hide()
59
+ # o mesmo para os cartoes novos
60
+ checked_portion = $("input[type='radio'][name='portions']:checked").val()
61
+ if parseInt(checked_portion) > 0
62
+ $('#payment_portions').val(checked_portion)
63
+ else
64
+ $('#payment_portions').val('1')
65
+
66
+ # Faz uma requisicao para pegar as parcelas disponiveis
67
+ # para o cartao existente
68
+ setPortionsCard: ->
69
+ card_checked = $('input[type=radio][name="order[existing_card]"]:checked').val()
70
+ cielo_cards = JSON.parse($('#has_cielo_credit').val())
71
+ if $.inArray(parseInt(card_checked), cielo_cards) >= 0
72
+ params =
73
+ credit_card_id: card_checked
74
+ prefix: 'existing_card_'
75
+ $.ajax
76
+ url: Spree.routes.portions(Spree.current_order_id)
77
+ data: params
78
+ dataType: 'html'
79
+ success: (response) ->
80
+ $('#portions_existing_cards').html(response)
81
+ $('input[type="radio"][name="existing_card_portions"]').click => setPortionsValue('existing_card_')
82
+ error: (xhr) ->
83
+ $('#portions_existing_cards').html(xhr.responseText)
84
+
85
+ # Insere o valor da parcela selecionada
86
+ setPortionsValue = (prefix) ->
87
+ checked_portion = $("input[type='radio'][name='#{prefix}portions']:checked").val()
88
+ $('#payment_portions').val(checked_portion)
89
+
90
+ # Seta os listeners do formulario
91
+ setListeners: ->
92
+ $('#cielo_card_number').on 'input', @setCreditCard
93
+ $('div[data-hook="checkout_payment_step"] input[type="radio"]').click => do @verifySaveButtonVisibility
94
+ $('input[type=radio][name="order[existing_card]"]').click => do @setPortionsCard
95
+
96
+ # Insere a rota das parcelas no objeto que guarda as rotas
97
+ setRoutes: ->
98
+ Spree.routes.portions = (order_id) ->
99
+ Spree.pathFor("api/orders/#{order_id}/portions")
100
+
101
+ # Verifica a mudanca da escolha do tipo de pagamento
102
+ # Se a escolhida nao for a CieloCredit retorna para 1 parcela
103
+ verifySaveButtonVisibility: ->
104
+ info = do @getCreditInfo
105
+ checkedMethod = $('div[data-hook="checkout_payment_step"] input[type="radio"][name="order[payments_attributes][][payment_method_id]"]:checked')
106
+ unless info.payment_method_id and info.payment_method_id.toString() == checkedMethod.val()
107
+ $('#payment_portions').val('1')
@@ -0,0 +1,123 @@
1
+ #= require_self
2
+ class window.CieloDebt
3
+ afterConstructor: ->
4
+
5
+ beforeConstructor: ->
6
+
7
+ constructor: (@debt_info, defaultExecution = true) ->
8
+ do @beforeConstructor
9
+ do @defaultExecution if defaultExecution
10
+ do @afterConstructor
11
+
12
+ defaultExecution: ->
13
+ $('#cielo_debt_number').on 'input', @setCreditCard
14
+ $('#cielo_debt_authorize').click (e) => @authorizePayment(e)
15
+ $('div[data-hook="checkout_payment_step"] input[type="radio"]').click => do @verifySaveButtonVisibility
16
+
17
+ # Antes de fazer a requisicao a Cielo
18
+ # verifica se o usuario inseriu um codigo de desconto
19
+ # se sim, aplica ele ao pedido e faz a requisicao
20
+ # se nao, exibe uma mensagem de erro e nao faz a requisicao
21
+ authorizePayment: (e) ->
22
+ e.preventDefault()
23
+ $(e.target).attr('disabled', true).removeClass('primary').addClass 'disabled'
24
+ info = do @getDebtInfo
25
+ # aplica o cupom de desconto se existir
26
+ coupon_code_field = $('#order_coupon_code')
27
+ coupon_code = $.trim(coupon_code_field.val())
28
+ if (coupon_code != '')
29
+ if $('#coupon_status').length == 0
30
+ coupon_status = $("<div id='coupon_status'></div>")
31
+ coupon_code_field.parent().append(coupon_status)
32
+ else
33
+ coupon_status = $("#coupon_status")
34
+
35
+ url = Spree.url(Spree.routes.apply_coupon_code(Spree.current_order_id),
36
+ {
37
+ order_token: Spree.current_order_token,
38
+ coupon_code: coupon_code
39
+ }
40
+ )
41
+
42
+ coupon_status.removeClass()
43
+
44
+ $.ajax({
45
+ async: false,
46
+ method: "PUT",
47
+ url: url,
48
+ success: (data) ->
49
+ coupon_code_field.val('')
50
+ coupon_status.addClass("alert-success").html("Coupon code applied successfully.")
51
+ makeRequestToCieloDebt(info)
52
+ error: (xhr) ->
53
+ handler = JSON.parse(xhr.responseText)
54
+ coupon_status.addClass("alert-error").html(handler["error"])
55
+ $('.continue').attr('disabled', false)
56
+ $(e.target).attr('disabled', false).addClass('primary').removeClass 'disabled'
57
+ return false
58
+ })
59
+
60
+ else
61
+ makeRequestToCieloDebt(info)
62
+
63
+ # Faz uma requisicao enviando as informacoes do cartao
64
+ # se ocorrer tudo bem, redireciona para a pagina do banco para a autenticacao
65
+ # se nao, exibe a mensagem de erro
66
+ makeRequestToCieloDebt = (info) ->
67
+ # verifica o tipo de cartao
68
+ cc_type = $('#cielo_debt_cc_type').val()
69
+ cc_type = 'master' if cc_type == 'mastercard' or cc_type == 'maestro'
70
+ cc_type = 'visa' if cc_type == 'visaelectron'
71
+ params =
72
+ guest_token: Spree.current_order_token
73
+ payment_method_id: info.payment_method_id
74
+ source:
75
+ number: $('#cielo_debt_number').val()
76
+ name: $('#cielo_debt_name').val()
77
+ cc_type: cc_type
78
+ expiry: $('#cielo_debt_expiry').val()
79
+ verification_value: $('#cielo_debt_code').val()
80
+ $.ajax
81
+ method: 'post'
82
+ url: '/cielo_debt/create'
83
+ data: params
84
+ success: (json) ->
85
+ window.location.replace json.url_auth
86
+ $('#cielo_debt_authorize').attr('disabled', false).addClass('primary').removeClass 'disabled'
87
+ error: (xhr) ->
88
+ if xhr.responseJSON == undefined
89
+ $('#cielo_debt_message').html(xhr.responseText)
90
+ else
91
+ $('#errorExplanationCielo').html(xhr.responseJSON.error)
92
+ $('#errorExplanationCielo').fadeIn()
93
+ $('#cielo_debt_authorize').attr('disabled', false).addClass('primary').removeClass 'disabled'
94
+
95
+ # Retorna o objeto que guarda as informacoes do pagamento
96
+ # (tipo de pagamento e total do pedido)
97
+ getDebtInfo: ->
98
+ @debt_info
99
+
100
+ # Verifica se o cartao que esta sendo digitado esta disponivel
101
+ # para a loja
102
+ setCreditCard: ->
103
+ $('#cielo_unrecognized').hide()
104
+ type = $.payment.cardType($('#cielo_debt_number').val())
105
+ type = 'master' if type == 'mastercard'
106
+ if type == null
107
+ $('#cielo_debt_unrecognized').show()
108
+ else
109
+ $('#cielo_debt_message').html("<img src='/assets/credit_cards/icons/#{type}.png' class='pull-right' />")
110
+ $('#cielo_debt_unrecognized').hide()
111
+ $('#cielo_debt_cc_type').val(type)
112
+
113
+ # Verifica se deve esconder/exibir o botao de confirmacao do pagamento
114
+ # Para debito, o pagamento e criado apenas apos a autenticacao,
115
+ # por isso, e necessario outro botao (e rota)
116
+ verifySaveButtonVisibility: ->
117
+ info = do @getDebtInfo
118
+ checkedMethod = $('div[data-hook="checkout_payment_step"] input[type="radio"][name="order[payments_attributes][][payment_method_id]"]:checked')
119
+ if info.payment_method_id and info.payment_method_id.toString() == checkedMethod.val()
120
+ $("#checkout_form_payment [data-hook=buttons]").hide()
121
+ else
122
+ $('#errorExplanationCielo').hide()
123
+ $("#checkout_form_payment [data-hook=buttons]").show()