unlock_moip 0.0.4

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 41a64ef8cd2d508986e5ddd50573d896613c1a80
4
+ data.tar.gz: c3ae96b599ef0ffaf34da169d832ade5590f4c27
5
+ SHA512:
6
+ metadata.gz: 74cbfea0a95ea10009b62ce7afffef87315656abe05a462da72b456a0d201801649ca5135529fa7841f3ba2f652b8fca7139f47bccf60f17c7a41255f3ecfe44
7
+ data.tar.gz: 809204b80f664b5ecf6ae0bc9e8943655492376be2f5b4ec5e9fdc844a9e4205621647484331413a7ed5279324928f1dbc3147c7588a42b26670c674bcdc4cef
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2014 YOURNAME
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Rakefile ADDED
@@ -0,0 +1,21 @@
1
+ begin
2
+ require 'bundler/setup'
3
+ rescue LoadError
4
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
5
+ end
6
+
7
+ require 'rdoc/task'
8
+
9
+ RDoc::Task.new(:rdoc) do |rdoc|
10
+ rdoc.rdoc_dir = 'rdoc'
11
+ rdoc.title = 'UnlockMoip'
12
+ rdoc.options << '--line-numbers'
13
+ rdoc.rdoc_files.include('README.rdoc')
14
+ rdoc.rdoc_files.include('lib/**/*.rb')
15
+ end
16
+
17
+
18
+
19
+
20
+ Bundler::GemHelper.install_tasks
21
+
@@ -0,0 +1,72 @@
1
+ $(document).ready ->
2
+ if action() == "new" and controller() == "contributions" and namespace() == "initiatives"
3
+ $('#contribution_value').maskMoney
4
+ thousands: ''
5
+ decimal: ''
6
+ precision: 0
7
+ if action() == "edit" and controller() == "contributions" and namespace() == "unlockmoip"
8
+ $('#pay_form [type=submit]').on "click", (event) ->
9
+ event.preventDefault()
10
+ event.stopPropagation()
11
+ billing_info_ok = false
12
+ form = $('#pay_form')
13
+ submit = form.find('[type=submit]')
14
+ status = form.find('.gateway_data')
15
+ terms = form.find('#terms')
16
+ status.removeClass 'success'
17
+ status.removeClass 'failure'
18
+ status.find('ul').html('')
19
+ unless terms.is(':checked')
20
+ status.addClass 'failure'
21
+ status.html("<h4>Você precisa aceitar os termos de uso para continuar.</h4>")
22
+ status.show()
23
+ else
24
+ status.html("<h4>Enviando dados de pagamento para o Moip...</h4><ul></ul>")
25
+ token = form.data('token')
26
+ plan_code = form.data('plan')
27
+ submit.hide()
28
+ status.show()
29
+ if MoipAssinaturas?
30
+ moip = new MoipAssinaturas(token)
31
+ moip.callback (response) ->
32
+ status.find('h4').html("#{response.message} (Moip)")
33
+ unless response.has_errors()
34
+ unless billing_info_ok
35
+ billing_info_ok = true
36
+ subscription = new Subscription()
37
+ subscription.with_code(form.data('subscription'))
38
+ subscription.with_customer(customer)
39
+ subscription.with_plan_code(plan_code)
40
+ moip.subscribe(subscription)
41
+ else
42
+ next_invoice = "#{response.next_invoice_date.day}/#{response.next_invoice_date.month}/#{response.next_invoice_date.year}"
43
+ $.ajax
44
+ url: form.data('activate'),
45
+ type: 'PUT',
46
+ dataType: 'json',
47
+ success: (response) ->
48
+ window.location.href = form.data('show')
49
+ error: (response) ->
50
+ status.find('h4').html("Não foi possível ativar sua assinatura")
51
+ status.addClass 'failure'
52
+ for error in response.responseJSON.errors
53
+ status.find('ul').append("<li>#{error}</li>")
54
+ submit.show()
55
+ else
56
+ status.addClass 'failure'
57
+ for error in response.errors
58
+ status.find('ul').append("<li>#{error.description}</li>")
59
+ submit.show()
60
+ billing_info =
61
+ fullname: $("#holder_name").val(),
62
+ expiration_month: $("#expiration_month").val(),
63
+ expiration_year: $("#expiration_year").val(),
64
+ credit_card_number: $("#number").val()
65
+ customer = new Customer()
66
+ customer.code = form.data('customer')
67
+ customer.billing_info = new BillingInfo(billing_info)
68
+ moip.update_credit_card(customer)
69
+ else
70
+ status.addClass 'failure'
71
+ status.find('h4').html("Erro ao carregar o Moip Assinaturas. Por favor, recarregue a página e tente novamente.")
72
+ submit.show()
@@ -0,0 +1,31 @@
1
+ body[data-action="edit"][data-controller="contributions"][data-namespace="unlockmoip"]
2
+ article
3
+ width: 92%
4
+ +media($tablet)
5
+ width: 90%
6
+ +media($desktop)
7
+ width: 70%
8
+ margin-left: auto
9
+ margin-right: auto
10
+ form
11
+ .field
12
+ float: left
13
+ width: 100%
14
+ margin-bottom: 0
15
+ .number
16
+ width: 47.5%
17
+ margin-right: 5%
18
+ .month
19
+ width: 21.25%
20
+ margin-right: 5%
21
+ .year
22
+ width: 21.25%
23
+ .value
24
+ margin-bottom: 2em
25
+ text-align: right
26
+ span
27
+ color: $link_color
28
+ font-size: 2em
29
+ .gateway_data
30
+ display: none
31
+ margin-bottom: 2em
@@ -0,0 +1,35 @@
1
+ body[data-action="new"][data-controller="contributions"][data-namespace="initiatives"], body[data-action="create"][data-controller="contributions"][data-namespace="unlockmoip"]
2
+ article
3
+ form
4
+ em
5
+ margin-bottom: 4em
6
+ .field
7
+ float: left
8
+ width: 100%
9
+ margin-bottom: 0
10
+ .document
11
+ width: 47.5%
12
+ margin-right: 5%
13
+ .birthdate
14
+ width: 47.5%
15
+ .street
16
+ width: 47.5%
17
+ margin-right: 5%
18
+ .number
19
+ width: 21.25%
20
+ margin-right: 5%
21
+ .complement
22
+ width: 21.25%
23
+ .district, .city, .state
24
+ width: 30%
25
+ margin-right: 5%
26
+ .state
27
+ margin-right: 0
28
+ .zipcode
29
+ width: 47.5%
30
+ margin-right: 5%
31
+ .phone_area_code
32
+ width: 12.5%
33
+ margin-right: 5%
34
+ .phone_number
35
+ width: 30%
@@ -0,0 +1,2 @@
1
+ @import contributions/form
2
+ @import contributions/edit
@@ -0,0 +1 @@
1
+ @import unlock_moip/unlock_moip
@@ -0,0 +1,199 @@
1
+ class UnlockMoip::ContributionsController < ::ApplicationController
2
+
3
+ inherit_resources
4
+ actions :create, :edit
5
+ custom_actions member: %i[activate suspend]
6
+ respond_to :html, except: [:activate, :suspend]
7
+ respond_to :json, only: [:activate, :suspend]
8
+
9
+ after_action :verify_authorized
10
+ after_action :verify_policy_scoped, only: %i[]
11
+ before_action :authenticate_user!, only: %i[edit]
12
+
13
+ def create
14
+
15
+ # Getting the date from Pickadate
16
+ if params[:pickadate_birthdate_submit]
17
+ params[:contribution][:user_attributes][:birthdate] = params[:pickadate_birthdate_submit]
18
+ end
19
+
20
+ # Creating the contribution
21
+ @initiative = Initiative.find(contribution_params[:initiative_id])
22
+ @gateways = @initiative.gateways.without_state(:draft).order(:ordering)
23
+ @contribution = @initiative.contributions.new(contribution_params)
24
+ @contribution.gateway_state = @contribution.gateway.state
25
+ authorize @contribution
26
+
27
+ if @contribution.save
28
+
29
+ data = {}
30
+ # Storing the customer_code and subscription_code
31
+ data["customer_code"] = @contribution.customer_code
32
+ data["subscription_code"] = @contribution.subscription_code
33
+ # Storing user information
34
+ data["email"] = @contribution.user.email
35
+ data["full_name"] = @contribution.user.full_name
36
+ data["document"] = @contribution.user.document
37
+ data["phone_area_code"] = @contribution.user.phone_area_code
38
+ data["phone_number"] = @contribution.user.phone_number
39
+ data["birthdate"] = @contribution.user.birthdate
40
+ data["address_street"] = @contribution.user.address_street
41
+ data["address_number"] = @contribution.user.address_number
42
+ data["address_complement"] = @contribution.user.address_complement
43
+ data["address_district"] = @contribution.user.address_district
44
+ data["address_city"] = @contribution.user.address_city
45
+ data["address_state"] = @contribution.user.address_state
46
+ data["address_zipcode"] = @contribution.user.address_zipcode
47
+ # Saving gateway_data
48
+ @contribution.update gateway_data: data
49
+
50
+ # Creating the plan, if needed
51
+ begin
52
+ response = Moip::Assinaturas::Plan.details(@contribution.plan_code, @contribution.moip_auth)
53
+ rescue Moip::Assinaturas::WebServerResponseError => e
54
+ if @contribution.gateway.sandbox?
55
+ @contribution.errors.add(:base, "Parece que este Unlock não está autorizado a utilizar o ambiente de Sandbox do Moip Assinaturas.#{ ' Você já solicitou acesso ao Moip Assinaturas? Verifique também se configurou o Token e a Chave de API.' if @initiative.user == current_user }")
56
+ else
57
+ @contribution.errors.add(:base, "Parece que este Unlock não está autorizado a utilizar o ambiente de produção do Moip Assinaturas.#{ ' Você já homologou sua conta para produção no Moip Assinaturas? Verifique também se configurou o Token e a Chave de API.' if @initiative.user == current_user }")
58
+ end
59
+ return render '/initiatives/contributions/new'
60
+ rescue => e
61
+ @contribution.errors.add(:base, "Ocorreu um erro de conexão ao verificar o plano de assinaturas no Moip. Por favor, tente novamente.")
62
+ return render '/initiatives/contributions/new'
63
+ end
64
+ unless response[:success]
65
+ plan = {
66
+ code: @contribution.plan_code,
67
+ name: @contribution.plan_name,
68
+ amount: (@contribution.value * 100).to_i
69
+ }
70
+ begin
71
+ response = Moip::Assinaturas::Plan.create(plan, @contribution.moip_auth)
72
+ rescue
73
+ @contribution.errors.add(:base, "Ocorreu um erro de conexão ao criar o plano de assinaturas no Moip. Por favor, tente novamente.")
74
+ return render '/initiatives/contributions/new'
75
+ end
76
+ unless response[:success]
77
+ if response[:errors] && response[:errors].kind_of?(Array)
78
+ response[:errors].each do |error|
79
+ @contribution.errors.add(:base, "#{response[:message]} (Moip). #{error[:description]}")
80
+ end
81
+ else
82
+ @contribution.errors.add(:base, "Ocorreu um erro ao criar o plano de assinaturas no Moip. Por favor, tente novamente.")
83
+ end
84
+ return render '/initiatives/contributions/new'
85
+ end
86
+ end
87
+
88
+ # Creating the client, if needed
89
+ customer = {
90
+ code: @contribution.customer_code,
91
+ email: @contribution.user.email,
92
+ fullname: @contribution.user.full_name,
93
+ cpf: @contribution.user.document,
94
+ phone_area_code: @contribution.user.phone_area_code,
95
+ phone_number: @contribution.user.phone_number,
96
+ birthdate_day: @contribution.user.birthdate.strftime('%d'),
97
+ birthdate_month: @contribution.user.birthdate.strftime('%m'),
98
+ birthdate_year: @contribution.user.birthdate.strftime('%Y'),
99
+ address: {
100
+ street: @contribution.user.address_street,
101
+ number: @contribution.user.address_number,
102
+ complement: @contribution.user.address_complement,
103
+ district: @contribution.user.address_district,
104
+ city: @contribution.user.address_city,
105
+ state: @contribution.user.address_state,
106
+ country: "BRA",
107
+ zipcode: @contribution.user.address_zipcode
108
+ }
109
+ }
110
+ begin
111
+ response = Moip::Assinaturas::Customer.details(@contribution.customer_code, @contribution.moip_auth)
112
+ rescue
113
+ @contribution.errors.add(:base, "Ocorreu um erro de conexão ao verificar o cadastro de cliente no Moip. Por favor, tente novamente.")
114
+ return render '/initiatives/contributions/new'
115
+ end
116
+ if response[:success]
117
+ begin
118
+ response = Moip::Assinaturas::Customer.update(@contribution.customer_code, customer, @contribution.moip_auth)
119
+ unless response[:success]
120
+ if response[:errors] && response[:errors].kind_of?(Array)
121
+ response[:errors].each do |error|
122
+ @contribution.errors.add(:base, "#{response[:message]} (Moip). #{error[:description]}")
123
+ end
124
+ else
125
+ @contribution.errors.add(:base, "Ocorreu um erro ao atualizar o cadastro de cliente no Moip. Por favor, tente novamente.")
126
+ end
127
+ return render '/initiatives/contributions/new'
128
+ end
129
+ rescue
130
+ @contribution.errors.add(:base, "Ocorreu um erro de conexão ao atualizar o cadastro de cliente no Moip. Por favor, tente novamente.")
131
+ return render '/initiatives/contributions/new'
132
+ end
133
+ else
134
+ begin
135
+ response = Moip::Assinaturas::Customer.create(customer, new_vault = false, @contribution.moip_auth)
136
+ rescue
137
+ @contribution.errors.add(:base, "Ocorreu um erro de conexão ao realizar o cadastro de cliente no Moip. Por favor, tente novamente.")
138
+ return render '/initiatives/contributions/new'
139
+ end
140
+ unless response[:success]
141
+ if response[:errors] && response[:errors].kind_of?(Array)
142
+ response[:errors].each do |error|
143
+ @contribution.errors.add(:base, "#{response[:message]} (Moip). #{error[:description]}")
144
+ end
145
+ else
146
+ @contribution.errors.add(:base, "Ocorreu um erro ao realizar o cadastro de cliente no Moip. Por favor, tente novamente.")
147
+ end
148
+ return render '/initiatives/contributions/new'
149
+ end
150
+ end
151
+
152
+ flash[:success] = "Apoio iniciado com sucesso! Agora é só realizar o pagamento :D"
153
+ return redirect_to edit_moip_contribution_path(@contribution)
154
+
155
+ else
156
+ return render '/initiatives/contributions/new'
157
+ end
158
+
159
+ end
160
+
161
+ def edit
162
+ edit! { authorize resource }
163
+ end
164
+
165
+ def activate
166
+ transition_state("activate", :active)
167
+ end
168
+
169
+ def suspend
170
+ transition_state("suspend", :suspended)
171
+ end
172
+
173
+ private
174
+
175
+ def transition_state(transition, state)
176
+ authorize resource
177
+ errors = []
178
+ if resource.send("can_#{transition}?")
179
+ begin
180
+ if resource.moip_state_name != state
181
+ response = Moip::Assinaturas::Subscription.send(transition.to_sym, resource.subscription_code, resource.moip_auth)
182
+ resource.send("#{transition}!") if response[:success]
183
+ else
184
+ resource.send("#{transition}!")
185
+ end
186
+ rescue
187
+ errors << "Não foi possível alterar o status de seu apoio."
188
+ end
189
+ else
190
+ errors << "Não é permitido alterar o status deste apoio."
191
+ end
192
+ render(json: {success: (errors.size == 0), errors: errors}, status: ((errors.size == 0) ? 200 : 422))
193
+ end
194
+
195
+ def contribution_params
196
+ params.require(:contribution).permit(*policy(@contribution || Contribution.new).permitted_attributes)
197
+ end
198
+
199
+ end
@@ -0,0 +1,61 @@
1
+ = form_for @contribution, url: moip_contributions_path, method: :post do |form|
2
+ - if gateway.sandbox?
3
+ .warning
4
+ h3 Atenção! Este unlock encontra-se em modo de testes (Sandbox) no Moip.
5
+ ul
6
+ li Nenhum apoio realizado neste modo será concretizado.
7
+ li Você pode testar livremente, sem medo de ser debitado.
8
+ - if @contribution.errors.any?
9
+ #error_explanation.warning
10
+ h3 = "#{pluralize(@contribution.errors.count, "erro impediu", "erros impediram")} que este apoio fosse salvo:"
11
+ ul
12
+ - @contribution.errors.full_messages.each do |msg|
13
+ li= msg
14
+ = form.hidden_field :user_id
15
+ = form.hidden_field :initiative_id
16
+ = form.hidden_field :gateway_id, value: gateway.id
17
+ h3 Com quanto você quer apoiar por mês?
18
+ = form.label :value
19
+ = form.text_field :value, class: "has_em"
20
+ em Assinatura mensal cobrada via cartão de crédito pelo meio de pagamentos #{link_to 'Moip', 'https://moip.com.br/', target: :_blank }. Você pode suspender #{ link_to 'a qualquer momento', my_contributions_path, target: :_blank }.
21
+ h3 Preencha e revise os dados para pagamento
22
+ = form.fields_for :user do |user_fields|
23
+ = user_fields.hidden_field :id
24
+ .field
25
+ = user_fields.label :full_name
26
+ = user_fields.text_field :full_name
27
+ .field.document
28
+ = user_fields.label :document
29
+ = user_fields.text_field :document
30
+ .field.birthdate
31
+ = user_fields.label :birthdate
32
+ = text_field_tag :pickadate_birthdate, (@contribution.user.birthdate.strftime('%d/%m/%Y') if @contribution.user.birthdate), class: "date", placeholder: "Data de nascimento"
33
+ = user_fields.hidden_field :birthdate
34
+ .field.street
35
+ = user_fields.label :address_street
36
+ = user_fields.text_field :address_street
37
+ .field.number
38
+ = user_fields.label :address_number
39
+ = user_fields.text_field :address_number
40
+ .field.complement
41
+ = user_fields.label :address_complement
42
+ = user_fields.text_field :address_complement
43
+ .field.district
44
+ = user_fields.label :address_district
45
+ = user_fields.text_field :address_district
46
+ .field.city
47
+ = user_fields.label :address_city
48
+ = user_fields.text_field :address_city
49
+ .field.state
50
+ = user_fields.label :address_state
51
+ = user_fields.select :address_state, options_for_select(ActionView::Helpers::FormOptionsHelper::ESTADOS_BRASILEIROS, @contribution.user.address_state)
52
+ .field.zipcode
53
+ = user_fields.label :address_zipcode
54
+ = user_fields.text_field :address_zipcode
55
+ .field.phone_area_code
56
+ = user_fields.label :phone_area_code
57
+ = user_fields.text_field :phone_area_code
58
+ .field.phone_number
59
+ = user_fields.label :phone_number
60
+ = user_fields.text_field :phone_number
61
+ .submit= form.submit "Realizar pagamento"
@@ -0,0 +1,5 @@
1
+ ul
2
+ li Seu código de assinatura é <strong>#{@contribution.subscription_code}</strong>
3
+ li Seu pagamento ainda será processado pelo <a href='https://www.moip.com.br/' target='_blank'>Moip</a>.
4
+ li Se você quiser suspender seu apoio, basta acessar o menu <a href='/my_contributions'>Unlocks apoiados</a> a qualquer momento.
5
+ li Sua próxima cobrança será realizada em #{@contribution.next_invoice_date}.
@@ -0,0 +1,32 @@
1
+ - content_for :title do
2
+ = "Dados de pagamento"
3
+ - content_for :external_js do
4
+ script type="text/javascript" src="https://#{( @contribution.gateway.sandbox? ? 'sandbox' : 'api' )}.moip.com.br/moip-assinaturas.min.js"
5
+ form#pay_form autocomplete="off" data-token=@contribution.gateway.settings["token"] data-plan=@contribution.plan_code data-customer=@contribution.customer_code data-subscription=@contribution.subscription_code data-activate=activate_moip_contribution_path data-show=initiative_contribution_path(@contribution.initiative.id, @contribution)
6
+ - if @contribution.gateway.sandbox?
7
+ .warning
8
+ h3 Atenção! Este unlock encontra-se em modo de testes (Sandbox) no Moip.
9
+ ul
10
+ li Nenhum apoio realizado neste modo será concretizado.
11
+ li Você pode testar livremente, sem medo de ser debitado.
12
+ .field
13
+ = label_tag :holder_name, "Nome escrito no cartão de crédito"
14
+ = text_field_tag :holder_name, "", autocomplete: "off"
15
+ .field.number
16
+ = label_tag :number, "Número do cartão de crédito"
17
+ = text_field_tag :number, "", autocomplete: "off"
18
+ .field.month
19
+ = label_tag :expiration_month, "Mês de expiração"
20
+ = text_field_tag :expiration_month, "", autocomplete: "off"
21
+ .field.year
22
+ = label_tag :expiration_year, "Ano de expiração"
23
+ = text_field_tag :expiration_year, "", autocomplete: "off"
24
+ .field
25
+ = check_box_tag :terms, "1", true
26
+ = label_tag :terms, "Eu li e aceito os #{ link_to 'termos de uso', page_path('terms'), target: :_blank }.".html_safe
27
+ h4.value
28
+ = "Apoio de "
29
+ span= "R$ #{@contribution.display_value},00"
30
+ = "/mês"
31
+ .gateway_data
32
+ .submit= submit_tag "Confirmar pagamento"
@@ -0,0 +1,9 @@
1
+ require "moip-assinaturas"
2
+
3
+ # Configuring Moip
4
+ Moip::Assinaturas.config do |config|
5
+ config.sandbox = true
6
+ config.token = "NO_TOKEN_FOR_NOW"
7
+ config.key = "NO_KEY_FOR_NOW"
8
+ end
9
+ Moip::Assinaturas::Client.default_timeout 5
@@ -0,0 +1,4 @@
1
+ begin
2
+ Gateway.register 'UnlockMoip'
3
+ rescue
4
+ end
data/config/routes.rb ADDED
@@ -0,0 +1,10 @@
1
+ Rails.application.routes.draw do
2
+
3
+ resources :moip_contributions, controller: 'unlock_moip/contributions', only: [:create, :edit, :update], path: '/moip' do
4
+ member do
5
+ put :activate
6
+ put :suspend
7
+ end
8
+ end
9
+
10
+ end
@@ -0,0 +1,4 @@
1
+ # desc "Explaining what the task does"
2
+ # task :unlock_moip do
3
+ # # Task goes here
4
+ # end
@@ -0,0 +1,4 @@
1
+ module UnlockMoip
2
+ class Engine < ::Rails::Engine
3
+ end
4
+ end
@@ -0,0 +1,66 @@
1
+ module UnlockMoip
2
+ module Models
3
+ module Contribution
4
+
5
+ include UnlockGateway::Models::Contribution
6
+
7
+ def moip_auth
8
+ return {} unless self.gateway && self.gateway.settings
9
+ { moip_auth: { token: self.gateway.settings["token"], key: self.gateway.settings["key"], sandbox: self.gateway.sandbox? }}
10
+ end
11
+
12
+ def plan_code
13
+ "#{self.initiative.permalink[0..29]}#{self.value.to_i}#{'sandbox' if self.gateway.sandbox?}"
14
+ end
15
+
16
+ def plan_name
17
+ "#{self.initiative.name[0..29]} #{self.value.to_i}#{' (Sandbox)' if self.gateway.sandbox?}"
18
+ end
19
+
20
+ def customer_code
21
+ if self.gateway_data && self.gateway_data["customer_code"]
22
+ self.gateway_data["customer_code"]
23
+ else
24
+ Digest::MD5.new.update("#{self.initiative.permalink[0..29]}#{self.user.id}#{'sandbox' if self.gateway.sandbox?}").to_s
25
+ end
26
+ end
27
+
28
+ def subscription_code
29
+ if self.gateway_data && self.gateway_data["subscription_code"]
30
+ self.gateway_data["subscription_code"]
31
+ else
32
+ Digest::MD5.new.update("#{self.initiative.permalink[0..29]}#{self.id}#{'sandbox' if self.gateway.sandbox?}").to_s
33
+ end
34
+ end
35
+
36
+ def moip_state_name
37
+ begin
38
+ response = Moip::Assinaturas::Subscription.details(self.subscription_code, self.moip_auth)
39
+ rescue
40
+ return nil
41
+ end
42
+ if response && response[:success]
43
+ status = (response[:subscription]["status"].upcase rescue nil)
44
+ case status
45
+ when 'ACTIVE', 'OVERDUE'
46
+ :active
47
+ when 'SUSPENDED', 'EXPIRED', 'CANCELED'
48
+ :suspended
49
+ end
50
+ end
51
+ end
52
+
53
+ def update_state_from_gateway!
54
+ if self.state_name != self.moip_state_name
55
+ case self.moip_state_name
56
+ when :active
57
+ self.activate! if self.can_activate?
58
+ when :suspended
59
+ self.suspend! if self.can_suspend?
60
+ end
61
+ end
62
+ end
63
+
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,32 @@
1
+ module UnlockMoip
2
+ module Models
3
+ module Gateway
4
+
5
+ include UnlockGateway::Models::Gateway
6
+
7
+ def name
8
+ "Moip Assinaturas"
9
+ end
10
+
11
+ def description
12
+ "Gerencie mensalidades, assinaturas e cobranças recorrentes com o Moip"
13
+ end
14
+
15
+ def image
16
+ "unlock_moip/logo.png"
17
+ end
18
+
19
+ def path
20
+ "/moip"
21
+ end
22
+
23
+ def available_settings
24
+ settings = []
25
+ instructions = "Com sua conta de negócios Moip habilitada, vá em <a href='https://www.moip.com.br/AdmMainMenuMyData.do?method=assinaturas' target='_blank'>Ferramentas › Moip Assinaturas</a> e clique em Habilitar acesso. Depois, vá em <a href='https://www.moip.com.br/AdmAPI.do?method=keys' target='_blank'>Ferramentas › API Moip › Chaves de acesso</a>."
26
+ settings << UnlockGateway::Setting.new(:token, "Token de acesso no Moip", instructions)
27
+ settings << UnlockGateway::Setting.new(:key, "Chave de acesso no Moip", instructions)
28
+ end
29
+
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,3 @@
1
+ module UnlockMoip
2
+ VERSION = "0.0.4"
3
+ end
@@ -0,0 +1,7 @@
1
+ require "unlock_gateway"
2
+ require "unlock_moip/engine"
3
+ require "unlock_moip/models/gateway"
4
+ require "unlock_moip/models/contribution"
5
+
6
+ module UnlockMoip
7
+ end
metadata ADDED
@@ -0,0 +1,121 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: unlock_moip
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.4
5
+ platform: ruby
6
+ authors:
7
+ - Daniel Weinmann
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2014-11-08 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rails
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ~>
18
+ - !ruby/object:Gem::Version
19
+ version: 4.1.6
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ~>
25
+ - !ruby/object:Gem::Version
26
+ version: 4.1.6
27
+ - !ruby/object:Gem::Dependency
28
+ name: moip-assinaturas
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - '='
32
+ - !ruby/object:Gem::Version
33
+ version: 0.4.2
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - '='
39
+ - !ruby/object:Gem::Version
40
+ version: 0.4.2
41
+ - !ruby/object:Gem::Dependency
42
+ name: unlock_gateway
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - '='
46
+ - !ruby/object:Gem::Version
47
+ version: 0.0.5
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - '='
53
+ - !ruby/object:Gem::Version
54
+ version: 0.0.5
55
+ - !ruby/object:Gem::Dependency
56
+ name: sqlite3
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - '>='
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - '>='
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ description: Moip Assinaturas integration with Unlock
70
+ email:
71
+ - danielweinmann@gmail.com
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - MIT-LICENSE
77
+ - Rakefile
78
+ - app/assets/images/unlock_moip/logo.png
79
+ - app/assets/javascripts/unlock_moip.js.coffee
80
+ - app/assets/stylesheets/unlock_moip.sass
81
+ - app/assets/stylesheets/unlock_moip/contributions/edit.sass
82
+ - app/assets/stylesheets/unlock_moip/contributions/form.sass
83
+ - app/assets/stylesheets/unlock_moip/unlock_moip.sass
84
+ - app/controllers/unlock_moip/contributions_controller.rb
85
+ - app/views/unlock_moip/contributions/_form.html.slim
86
+ - app/views/unlock_moip/contributions/_gateway_data.html.slim
87
+ - app/views/unlock_moip/contributions/edit.html.slim
88
+ - config/initializers/moip_assinaturas.rb
89
+ - config/initializers/register.rb
90
+ - config/routes.rb
91
+ - lib/tasks/unlock_moip_tasks.rake
92
+ - lib/unlock_moip.rb
93
+ - lib/unlock_moip/engine.rb
94
+ - lib/unlock_moip/models/contribution.rb
95
+ - lib/unlock_moip/models/gateway.rb
96
+ - lib/unlock_moip/version.rb
97
+ homepage: https://github.com/danielweinmann/unlock_moip
98
+ licenses:
99
+ - MIT
100
+ metadata: {}
101
+ post_install_message:
102
+ rdoc_options: []
103
+ require_paths:
104
+ - lib
105
+ required_ruby_version: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - '>='
108
+ - !ruby/object:Gem::Version
109
+ version: '0'
110
+ required_rubygems_version: !ruby/object:Gem::Requirement
111
+ requirements:
112
+ - - '>='
113
+ - !ruby/object:Gem::Version
114
+ version: '0'
115
+ requirements: []
116
+ rubyforge_project:
117
+ rubygems_version: 2.4.2
118
+ signing_key:
119
+ specification_version: 4
120
+ summary: Moip Assinaturas integration with Unlock
121
+ test_files: []