Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Maiz committed Feb 25, 2010
0 parents commit fda8935
Show file tree
Hide file tree
Showing 9 changed files with 382 additions and 0 deletions.
20 changes: 20 additions & 0 deletions MIT-LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Copyright (c) 2006 Cosmin Radoi

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
52 changes: 52 additions & 0 deletions README
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
DataGrid
==============

== Resources

Install
* Run the following command:
script/plugin install @TODO colocar no github for free...

* Create a new rails migration and add the following self.up and self.down methods

def self.up
create_table "ratings", :force => true do |t|
t.column "rating", :integer, :default => 0
t.column "created_at", :datetime, :null => false
t.column "rateable_type", :string, :limit => 15, :default => "", :null => false
t.column "rateable_id", :integer, :default => 0, :null => false
t.column "user_id", :integer, :default => 0, :null => false
end

add_index "ratings", ["user_id"], :name => "fk_ratings_user"
end

def self.down
drop_table :ratings
end

== Usage
* Make you ActiveRecord model act as rateable.

class Model < ActiveRecord::Base
acts_as_rateable
end

* Add a rating to a model instance

model = Model.new
rating = Rating.new(:rating => 1)
model.ratings << rating

* Each rating references the rateable object

model = Model.find(1)
model.ratings.get(0).rateable == model

== Credits

Xelipe - This plugin is heavily influced by Acts As Voteable.

== More

http://www.juixe.com/projects/acts_as_rateable
5 changes: 5 additions & 0 deletions config/komerci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
:komerci:
:filiation: 23254866
:process_url: http://softa.localhost:3000/store/order/confirm
:top_url: http://localhost:3000
10 changes: 10 additions & 0 deletions init.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Include hook code here
require 'komerci'
#require 'acts_as_data_grid'
#ActiveRecord::Base.send(:include, Softa::DataGrid::Acts)
#ActionController::Base.send(:include, Softa::Uses::DataGrid)
#ActionController::Base.send(:include, Softa::DataGrid::Uses)

ActionView::Base.send(:include, Komerci::Helper)
# http://activerecord.rubyonrails.org/2007/2/4/new-feature-for-rails-2-0-multiple-controller-view-paths
ActionController::Base.view_paths.unshift File.join(directory, 'views')
3 changes: 3 additions & 0 deletions install.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Install hook code here
require 'fileutils'
FileUtils.copy "config/komerci.yml", "../../../config/komerci.yml"
159 changes: 159 additions & 0 deletions lib/komerci.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
#53083516351-643
#530835163.051-643
# ,sn=nil
#sn||
class Komerci

CONFIRMATION_STATUS = {
0 => "Confirmação com sucesso",
1 => "Já confirmada (transação já confirmada anteriormente)",
2 => "Transação negada",
3 => "Transação desfeita (ultrapassado o tempo disponível para confirmação)",
4 => "Transação estornada",
5 => "Transação estornada",
8 => "Dados não coincidem",
9 => "Transação não encontrada",
88 => "Dados ausentes. Transação não pode ser concluída"
}

class OrderIdDoesntMatchException < StandardError; end
class ReturnCodeException < StandardError; end
class InvalidTransactionDataException < StandardError; end

class Server
def self.send_confirmation data
get = data.collect { |key, value| "#{key}=#{CGI.escape(value.to_s)}" }.join("&")
url = "http://ecommerce.redecard.com.br/pos_virtual/confirma.asp?#{get}"
require 'open-uri'
open(url) do |result|
params = CGI::parse(result.read)
new_params = {}
require 'iconv'
i = Iconv.new 'UTF-8', 'ISO-8859-1'
params.each_pair{|k,v| new_params[k.downcase] = i.iconv(v.first) }
return new_params
end
end
end

def self.code(filiation,total,ip,now=nil)
s = [11,17,21,31,56,34,42,3,18,13,12,18,22,32,57,35,43,4,19,14,9,20,23,33,58,6,44,5,24,15, 62,25,34,59,37,45,6,25,16,27,63,26,35,60,38,46,7,26,17,28,14,36,2,39,47,8,29,22,55,33][now||Time.now.sec]
pad = s < 10 ? '0' : ''
total_i = total.to_i
i5 = (s + total).to_i
i6 = s + ip.size
i7 = s * filiation.to_i
i8 = i7.to_s.size
"#{i7}#{i5}#{i6}-#{i8}#{pad}#{s}"
end

@@config = nil
def self.get_config
return @@config if @@config
content = File.read("#{Rails.root}/config/komerci.yml")
@@config = OpenStruct.new(YAML.load(content)[:komerci])
end

def initialize order_id, order_total, params
@order_id, @order_total, @params = order_id, order_total, params
if( @order_id != @params['NUMPEDIDO'].to_i )
raise OrderIdDoesntMatchException, 'Erro ao processar pagamento'
end
@config = Komerci.get_config
end

def process

# Transação aprovada
#NOME TAMANHO DESCRIÇÃO
#DATA 8 Data da transação
#NUMPEDIDO 16 Número do Pedido 26
#NR_CARTAO 16 Número do Cartão mascarado 548649******4015
#ORIGEM_BIN 3 Código de Nacionalidade do Emissor
#NUMAUTOR 6 Número de Autorização
#NUMCV 9 Número do Comprovante de Venda (NSU)
#NUMAUTENT 27 Número de Autenticação
#NUMSQN 12 Número seqüencial único

# Transação não aprovada
#NOME TAMANHO DESCRIÇÃO
#NUMPEDIDO 16 Número do Pedido
#CODRET 2 Código de erro
#MSGRET 200 Mensagem de erro

@transaction_data = {}
require 'iconv'
i = Iconv.new 'UTF-8', 'ISO-8859-1'
@params.each_pair{|k,v| @transaction_data[k.downcase] = i.iconv(v) if ! ['action','controller'].include? k }

if @params['CODRET'] and @params['CODRET'].to_i > 49
raise ReturnCodeException, @params['MSGRET']
end

return @transaction_data
end


def confirm
raise InvalidTransactionDataException, 'Erro ao processar pagamento' unless @transaction_data
# :Transação => 203, #3 Código da transação de confirmação
# :Transação => 88, #3 Código da transação de confirmação
#TODO tem q ver se é 04 mesmo e colocar no config!
data = {
:data => @transaction_data[:data], #8 Data da transação
:transorig => '04', #2 Código do tipo da transação original
:parcelas => '00', #2 Número de parcelas da transação
:filiacao => @config.filiation, #9 Filiação do estabelecimento (fornecedor)
:distribuidor => '', #9 Filiação do estabelecimento (distribuidor)
# :total => order.total, #15 Valor da transação
:total => @order_total, #15 Valor da transação
:numpedido => @transaction_data[:numpedido], #16 Número do pedido
:numautor => @transaction_data[:numautor], #6 Número da autorização
:numcv => @transaction_data[:numcv], #9 Número do Comprovante de Vendas
:numsqn => @transaction_data[:numsqn] #12 Número seqüencial único
}
@confirmation_data = Komerci::Server.send_confirmation data
# raise @confirmation_data['codret'].inspect + "!!!!!!!!!!!!"

if @confirmation_data['codret'].to_i == 0
true
else
@error = @confirmation_data['msgret']
false
end
end

attr_reader :transaction_data, :confirmation_data, :error
# def transaction_data
# @transaction_data
# end
# def confirmation_data
# @confirmation_data
# end


module Helper
##
# order
# - must be an AR instance, with a "total" method
# card
# - :mastercard or :dinners

##
def komerci_form order, card=:master, options={}
@card = card
# @card = options[:card] || :mastercard
# @process_url = options[:process_url] || "http://softa.localhost:3000"+confirmation_store_order_path(:locale => nil)
# 'http://localhost:3000'
@config = Komerci.get_config
options.each{|option,value| @config.send("#{option}=",value)}

# raise @config.inspect
@order = order
render :partial => 'komerci/form'
end
end

end


3 changes: 3 additions & 0 deletions test/komerci_mock.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
class KomerciServer
end
Product.expects(:find).with(1).returns(product)
110 changes: 110 additions & 0 deletions test/komerci_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
#require 'helper'
require 'test/unit'
require 'rubygems'
require 'mocha'
#raise Rails.root

# Add your module file here
require File.dirname(__FILE__) + '/../lib/komerci'



class KomerciTest < Test::Unit::TestCase

def setup ; end

def test_code
#send 1 and 30 as the second...
assert_equal '39533272225128-917', Komerci.code(23254866,234.56,'192.168.0.1',1)
assert_equal '144180169218577-1062', Komerci.code(23254866,123.45,'200.195.156.133',30)
assert_equal '76543203618577-962', Komerci.code(12345678,123.45,'200.195.156.133',30)
end

def test_process_numpedido_errado
Komerci.stubs(:get_config).returns({})
params = {'NUMPEDIDO' => '12'}
assert_raise(Komerci::OrderIdDoesntMatchException) do
Komerci.new(11, 100, params).process
end
end

def test_process_return_error
Komerci.stubs(:get_config).returns({})
params = {'NUMPEDIDO' => '12', 'CODRET' => '50', 'MSGRET' => 'Erro de teste'}
exception = assert_raise(Komerci::ReturnCodeException) do
Komerci.new(12, 100, params).process
end
assert_equal 'Erro de teste', exception.to_s
end


#NOME TAMANHO DESCRIÇÃO
#DATA 8 Data da transação
#NUMPEDIDO 16 Número do Pedido 26
#NR_CARTAO 16 Número do Cartão mascarado 548649******4015
#ORIGEM_BIN 3 Código de Nacionalidade do Emissor
#NUMAUTOR 6 Número de Autorização
#NUMCV 9 Número do Comprovante de Venda (NSU)
#NUMAUTENT 27 Número de Autenticação
#NUMSQN 12 Número seqüencial único

def test_process_success
Komerci.stubs(:get_config).returns({})
date = Date.today.strftime('%d%m%Y')
params = {'NUMPEDIDO' => '12', 'CODRET' => '2', 'DATA' => date, 'NR_CARTAO' => '548649******4015', 'ORIGEM_BIN' => '001', 'NUMAUTOR' => '123456', 'NUMCV' => '123456789', }
expected = {'numpedido' => '12', 'codret' => '2', 'data' => date, 'nr_cartao' => '548649******4015', 'origem_bin' => '001', 'numautor' => '123456', 'numcv' => '123456789', }
assert_equal expected, Komerci.new(12, 100, params).process
end

def test_confirm_invalid_transaction_data
Komerci.stubs(:get_config).returns({})
assert_raise(Komerci::InvalidTransactionDataException) do
Komerci.new(12, 123, {'NUMPEDIDO' => '12'}).confirm
end
end

def test_confirm_with_error
require 'ostruct'
Komerci.stubs(:get_config).returns(OpenStruct.new({:filiation => 123456}))
date = Date.today.strftime('%d%m%Y')
params = {'NUMPEDIDO' => '12', 'CODRET' => '2', 'DATA' => date, 'NR_CARTAO' => '548649******4015', 'ORIGEM_BIN' => '001', 'NUMAUTOR' => '123456', 'NUMCV' => '123456789', }

Komerci::Server.stubs(:send_confirmation).returns({'codret' => '1'})

k = Komerci.new(12, 123, params)
k.process
assert ! k.confirm
end

def test_confirm
require 'ostruct'
Komerci.stubs(:get_config).returns(OpenStruct.new({:filiation => 123456}))
date = Date.today.strftime('%d%m%Y')
params = {'NUMPEDIDO' => '12', 'CODRET' => '2', 'DATA' => date, 'NR_CARTAO' => '548649******4015', 'ORIGEM_BIN' => '001', 'NUMAUTOR' => '123456', 'NUMCV' => '123456789', }

Komerci::Server.stubs(:send_confirmation).returns({:codret => '0'})

k = Komerci.new(12, 123, params)
k.process
assert k.confirm
end



# def test_confirm
# Komerci.stubs(:get_config).returns({})
# date = Date.today.strftime('%d%m%Y')
# params = {'NUMPEDIDO' => '12', 'CODRET' => '2', 'DATA' => date, 'NR_CARTAO' => '548649******4015', 'ORIGEM_BIN' => '001', 'NUMAUTOR' => '123456', 'NUMCV' => '123456789', }
# expected = {'numpedido' => '12', 'codret' => '2', 'data' => date, 'nr_cartao' => '548649******4015', 'origem_bin' => '001', 'numautor' => '123456', 'numcv' => '123456789', }
# assert_equal expected, Komerci.new.confirm(12, params)
# end


# order = Order.new
# assert order
# order.expects(:id).returns(11)
# order.expects(:state).returns()
# order.expects(:update_attribute).with(:p1,:p2).returns(true)
# assert_equal :in_progress, order.state
# assert_equal :failed, order.state
end
20 changes: 20 additions & 0 deletions views/komerci/_form.haml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
%form{ :name => :form_pos, :action => "https://ecommerce.redecard.com.br/pos_virtual/form_card.asp", :method => :post, :target => :vredecard }
%input{ :name => "TOTAL", :value => ("%.2f" % @order.total), :type => "hidden" }
// À vista 04
// Parcelado Emissor 06
// Parcelado Estabelecimento 08
%input{ :name => "TRANSACAO", :value => "04", :type => "hidden" }
%input{ :name => "PARCELAS", :value => "00", :type => "hidden" }
%input{ :name => "BANDEIRA", :value => @card.to_s.upcase, :type => "hidden" }
%input{ :name => "FILIACAO", :value => @config.filiation, :type => "hidden" }
%input{ :name => "URLBACK", :value => @config.process_url, :type => "hidden" }
%input{ :name => "NUMPEDIDO", :value => @order.id, :type => "hidden" }
%input{ :name => "CODVER", :value => Komerci.code(@config.filiation, @order.total, '10.0.0.180'), :type => "hidden" }
%input{ :name => "DISTRIBUIDOR", :value => "", :type => "hidden" }
%input{ :name => "PAX1", :value => "pt_BR", :type => "hidden" }
//TODO muito importante: colocar na config a URLCIMA (customiza a interface da Redecard)
%input{ :name => "URLCIMA", :value => @config.top_url, :type => "hidden" }
%input{ :name => "TARGET", :value => "", :type => "hidden" }
%script
vredecard=window.open('','vredecard','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=800,height=460');
document.form_pos.submit();

0 comments on commit fda8935

Please sign in to comment.