Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Controle adicional no limite de dimensões #20

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
5 changes: 4 additions & 1 deletion CHANGELOG.rdoc
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
== Versão 1.9.3
== Versão 1.9.5
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Atualização de versão é feita somente no branch master.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Certo, me ficou uma dúvida: posso arrancar o texto numa boa? Você se encarrega de escrever outro texto para a mensagem de changelog?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sim.

- Adicionado tratamento de limites máximos de dimensões. Quando algum item de um pacote possui dimensões maiores que as permitidas pelos Correios, essas medidas são informadas diretamente ao webservice dos Correios.

== Versão 1.9.4
- Atualização: Versão 0.0.10 da gem log-me.

== Versão 1.9.3
Expand Down
38 changes: 37 additions & 1 deletion README.rdoc
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,43 @@ Montado o pacote, basta passá-lo pelo parâmetro <b>encomenda</b> no construtor
servicos[:pac].valor # => 13.3
servicos[:pac].prazo_entrega # => 5

<b>Observação:</b> Quando uma encomenda é fornecida ao calculador de frete, os parâmetros <b>peso</b>, <b>comprimento</b>, <b>largura</b>, <b>altura</b> e <b>formato</b> serão ignorados, sendo utilizados os valores da encomenda.
Caso alguma dimensão do pacote seja maior que o tamanho máximo permitido pelos correios, o valor máximo será atribuído à dimensão.

item1 = Correios::Frete::PacoteItem.new :peso => 0.3, :comprimento => 30, :largura => 15, :altura => 2
item2 = Correios::Frete::PacoteItem.new :peso => 0.7, :comprimento => 40, :largura => 10, :altura => 3
item3 = Correios::Frete::PacoteItem.new :peso => 0.7, :comprimento => 106, :largura => 10, :altura => 3

pacote = Correios::Frete::Pacote.new
pacote.adicionar_item(item1)
pacote.adicionar_item(item2)
pacote.adicionar_item(item3)

pacote.comprimento # => 106
pacote.largura # => 17.41317538234722
pacote.altura # => 17.41317538234722

Ao montar o pacote pode-se observar que os Correios retornam tratamentos condizentes com as limitações de tamanho.

frete = Correios::Frete::Calculador.new :cep_origem => "04094-050",
:cep_destino => "90619-900",
:encomenda => pacote

servicos = frete.calcular :sedex, :pac

servicos[:sedex].valor # => 0.0
servicos[:sedex].prazo_entrega # => 0
servicos[:sedex].msg_erro # => "O comprimento nao pode ser maior que 105 cm."

servicos[:pac].valor # => 0.0
servicos[:pac].prazo_entrega # => 0
servicos[:pac].msg_erro # => "O comprimento nao pode ser maior que 105 cm."


<b>Observação:</b>

Quando uma encomenda é fornecida ao calculador de frete, os parâmetros <b>peso</b>, <b>comprimento</b>, <b>largura</b>, <b>altura</b> e <b>formato</b>, quando dentro dos limites estabelecidos pelos Correios, serão ignorados, sendo utilizados os valores da encomenda.

Quando algum dos parâmetros <b>comprimento</b>, <b>largura</b>, <b>altura</b> for maior que o limite máximo estabelecido pelos Correios, o pacote receberá tal valor na respectiva dimensão, indicando aos Correios que ao menos um dos itens do pacote excede os limites e, portanto, o pacote não poderá ser enviado.

Usando a interface pública em inglês:

Expand Down
34 changes: 32 additions & 2 deletions lib/correios/frete/pacote.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ class Pacote
:altura => 2.0
}

MAX_DIMENSIONS = {
:comprimento => 105.0,
:largura => 105.0,
:altura => 105.0
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Você pode usar somente uma variável já que o limite máximo é o mesmo para todas as dimensões.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pensei em fazer isso, mas deixei de faze-lo por que achei que ficaria mais claro separa-las. Vou fazer uma só, tem preferência de nome? (pensei em altura_largura_comprimento)

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAX_DIMENSION


def initialize(itens = nil)
@peso = @comprimento = @largura = @altura = @volume = 0.0
@itens = []
Expand Down Expand Up @@ -48,8 +54,9 @@ def calcular_medidas(item)
@largura = item.largura
@altura = item.altura
else
dimensao = @volume.to_f**(1.0/3)
@comprimento = @largura = @altura = dimensao
@comprimento = comprimento_itens
@largura = largura_itens
@altura = altura_itens
end

min_dimension_values
Expand All @@ -64,6 +71,29 @@ def min_dimension_values()
def min(value, minimum)
(value < minimum) ? minimum : value
end

def max(value, maximum)
(value >= maximum) ? value : maximum
end

def dimensao
@volume.to_f**(1.0/3)
end

def comprimento_itens
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Um nome mais adequado para esse método seria calcular_comprimento.

max = @itens.map(&:comprimento).max
max >= MAX_DIMENSIONS[:comprimento] ? max : dimensao
end

def largura_itens
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Um nome mais adequado para esse método seria calcular_largura.

max = @itens.map(&:largura).max
max >= MAX_DIMENSIONS[:largura] ? max : dimensao
end

def altura_itens
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Um nome mais adequado para esse método seria calcular_altura.

max = @itens.map(&:altura).max
max >= MAX_DIMENSIONS[:altura] ? max : dimensao
end
end
end
end
2 changes: 1 addition & 1 deletion lib/correios/frete/version.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# encoding: UTF-8
module Correios
module Frete
VERSION = "1.9.4"
VERSION = "1.9.5"
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Atualização de versão é feita somente no branch master.

end
end
82 changes: 82 additions & 0 deletions spec/correios/frete/pacote_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,13 @@

@pacote.adicionar_item(@item1)
@pacote.adicionar_item(@item2)

@exceeded_dimensions = Correios::Frete::PacoteItem.new(
:altura => Correios::Frete::Pacote::MAX_DIMENSIONS[:altura] + 1,
:largura => Correios::Frete::Pacote::MAX_DIMENSIONS[:largura] + 1,
:comprimento => Correios::Frete::Pacote::MAX_DIMENSIONS[:comprimento] + 1,
:peso => 1.0
)
Copy link
Owner

@prodis prodis Aug 24, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Os valores excedidos de altura, largura e comprimento são iguais (106). Não há necessidade de se criar uma instância de PacoteItem somente para carregar esse valor.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdade cara. Comecei pensando em criar um item para adiciona-lo no pacote, mas depois mudei a abordagem e acabou ficando ali por nada. Valeu por chamar a atenção p isso.

end

it "calculates package weight" do
Expand Down Expand Up @@ -183,6 +190,81 @@
expect(@pacote.altura).to eq(2)
end
end

context "with at least one item dimension greater than maximum" do
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Na descrição do contexto está especificado "ao menos uma dimensão do item é maior que o máximo", mas os testes foram feitos com 3 itens de dimensão com tamanho excedido.

Talvez seria melhor testar cada dimensão separada.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Boa idéia :)

before :each do
over_lengthened = Correios::Frete::PacoteItem.new(:peso => 0.3, :largura => 1, :altura => 1,
:comprimento => @exceeded_dimensions.comprimento)

too_wide = Correios::Frete::PacoteItem.new(:peso => 0.3, :comprimento => 3, :altura => 1,
:largura => @exceeded_dimensions.largura)

over_heightened = Correios::Frete::PacoteItem.new(:peso => 0.3, :comprimento => 3, :largura => 1,
:altura => @exceeded_dimensions.altura)

@pacote = Correios::Frete::Pacote.new
@pacote.adicionar_item(over_lengthened)
@pacote.adicionar_item(too_wide)
@pacote.adicionar_item(over_heightened)
end

it "shows biggest length value" do
expect(@pacote.comprimento).to eq(@exceeded_dimensions.comprimento)
end

it "shows biggest width value" do
expect(@pacote.largura).to eq(@exceeded_dimensions.largura)
end

it "shows biggest height value" do
expect(@pacote.altura).to eq(@exceeded_dimensions.altura)
end
end

context "over lengthed items with zero widht and height" do
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo.

before :each do
over_lengthened = Correios::Frete::PacoteItem.new(:peso => 0.3, :largura => 0, :altura => 0,
:comprimento => @exceeded_dimensions.comprimento)

@pacote = Correios::Frete::Pacote.new
2.times{@pacote.adicionar_item(over_lengthened)}
end

it "does not get length information from minimum dimensions" do
expect(@pacote.items.size).to eq(2)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Não há necessidade dessa expectativa. Ela está verificando se o cenário de testes foi montado corretamente.

expect(@pacote.comprimento).to_not eq(Correios::Frete::Pacote::MIN_DIMENSIONS[:comprimento])
Copy link
Owner

@prodis prodis Aug 24, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Foi colocada a expectativa negativa, mas não há nenhuma expectativa positiva.

Sempre que se cria uma expectativa negativa em um teste, ela deve vir acompanhada de uma expectativa do valor que se espera obter.

Nesse teste, se @pacote.comprimento retornar nil por exemplo, o teste continua passando.

Copy link
Author

@aramisf aramisf Aug 25, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nossa, ótima dica! Muito bem lembrado, vou melhorar esse teste também.
Aguardo sua resposta sobre a parte do versionamento e a preferência de nome para a variável única com a dimensão máxima permitida para fazer o próximo commit.

end
end

context "over widthed items with zero length and height" do
before :each do
too_wide = Correios::Frete::PacoteItem.new(:peso => 0.3, :comprimento => 0, :altura => 0,
:largura => @exceeded_dimensions.largura)

@pacote = Correios::Frete::Pacote.new
2.times{@pacote.adicionar_item(too_wide)}
end

it "does not get width information from minimum dimensions" do
expect(@pacote.items.size).to eq(2)
expect(@pacote.largura).to_not eq(Correios::Frete::Pacote::MIN_DIMENSIONS[:largura])
end
end

context "over heighted items with zero widht and length" do
before :each do
over_heightened = Correios::Frete::PacoteItem.new(:peso => 0.3, :comprimento => 0, :largura => 0,
:altura => @exceeded_dimensions.altura)

@pacote = Correios::Frete::Pacote.new
2.times{@pacote.adicionar_item(over_heightened)}
end

it "does not get height information from minimum dimensions" do
expect(@pacote.items.size).to eq(2)
expect(@pacote.altura).to_not eq(Correios::Frete::Pacote::MIN_DIMENSIONS[:altura])
end
end
end
end
end