private cResultado ProcessShipping(GetShippingOptionRequest getShippingOptionRequest, GetShippingOptionResponse getShippingOptionResponse) { var usedMeasureWeight = _measureService.GetMeasureWeightBySystemKeyword(MEASURE_WEIGHT_SYSTEM_KEYWORD); if (usedMeasureWeight == null) { string e = string.Format("Plugin.Shipping.Correios: Could not load \"{0}\" measure weight", MEASURE_WEIGHT_SYSTEM_KEYWORD); _logger.Fatal(e); throw new NopException(e); } var usedMeasureDimension = _measureService.GetMeasureDimensionBySystemKeyword(MEASURE_DIMENSION_SYSTEM_KEYWORD); if (usedMeasureDimension == null) { string e = string.Format("Plugin.Shipping.Correios: Could not load \"{0}\" measure dimension", MEASURE_DIMENSION_SYSTEM_KEYWORD); _logger.Fatal(e); throw new NopException(e); } //Na versão 2.2 o getShippingOptionRequest.ZipPostalCodeFrom retorna string.Empty, possui um TODO... string cepOrigem = null; if (this._shippingSettings.ShippingOriginAddressId > 0) { var addr = this._addressService.GetAddressById(this._shippingSettings.ShippingOriginAddressId); if (addr != null && !String.IsNullOrEmpty(addr.ZipPostalCode) && addr.ZipPostalCode.Length >= 8 && addr.ZipPostalCode.Length <= 9) { cepOrigem = addr.ZipPostalCode; } } if (cepOrigem == null) { _logger.Fatal("Plugin.Shipping.Correios: CEP de Envio em branco ou inválido, configure nas opções de envio do NopCommerce.Em Administração > Configurações > Configurações de Envio. Formato: 00000000"); throw new NopException("Plugin.Shipping.Correios: CEP de Envio em branco ou inválido, configure nas opções de envio do NopCommerce.Em Administração > Configurações > Configurações de Envio. Formato: 00000000"); } var correiosCalculation = new CorreiosBatchCalculation(this._logger) { CodigoEmpresa = _correiosSettings.CodigoEmpresa, Senha = _correiosSettings.Senha, CepOrigem = cepOrigem, Servicos = _correiosSettings.CarrierServicesOffered, AvisoRecebimento = _correiosSettings.IncluirAvisoRecebimento, MaoPropria = _correiosSettings.IncluirMaoPropria, CepDestino = getShippingOptionRequest.ShippingAddress.ZipPostalCode }; decimal subtotalBase = decimal.Zero; decimal orderSubTotalDiscountAmount = decimal.Zero; Discount orderSubTotalAppliedDiscount = null; decimal subTotalWithoutDiscountBase = decimal.Zero; decimal subTotalWithDiscountBase = decimal.Zero; _orderTotalCalculationService.GetShoppingCartSubTotal(getShippingOptionRequest.Items, out orderSubTotalDiscountAmount, out orderSubTotalAppliedDiscount, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase); subtotalBase = subTotalWithDiscountBase; int length = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(getShippingOptionRequest.GetTotalLength(), usedMeasureDimension)) / 10); int height = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(getShippingOptionRequest.GetTotalHeight(), usedMeasureDimension)) / 10); int width = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(getShippingOptionRequest.GetTotalWidth(), usedMeasureDimension)) / 10); int weight = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureWeight(_shippingService.GetShoppingCartTotalWeight(getShippingOptionRequest.Items), usedMeasureWeight))); if (length < 1) length = 1; if (height < 1) height = 1; if (width < 1) width = 1; if (weight < 1) weight = 1; //Altura não pode ser maior que o comprimento, para evitar erro, igualamos e a embalagem deve ser adaptada. if (height > length) { length = height; } if (IsPackageTooSmall(length, height, width)) { length = MIN_PACKAGE_LENGTH; height = MIN_PACKAGE_HEIGHT; width = MIN_PACKAGE_WIDTH; } if ((!IsPackageTooHeavy(weight)) && (!IsPackageTooLarge(length, height, width))) { Debug.WriteLine("Plugin.Shipping.Correios: Pacote unico"); correiosCalculation.Pacotes.Add(new CorreiosBatchCalculation.Pacote() { Altura = height, Comprimento = length, Largura = width, Diametro = 0, FormatoPacote = true, Peso = weight, ValorDeclarado = (_correiosSettings.IncluirValorDeclarado ? subtotalBase : 0) }); return correiosCalculation.Calculate(); } else { int totalPackages = 1; int totalPackagesDims = 1; int totalPackagesWeights = 1; if (IsPackageTooHeavy(weight)) { totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)weight / (decimal)MAX_PACKAGE_WEIGHT)); } if (IsPackageTooLarge(length, height, width)) { totalPackagesDims = Convert.ToInt32(Math.Ceiling((decimal)TotalPackageSize(length, height, width) / (decimal)MAX_PACKAGE_TOTAL_DIMENSION)); } totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights; if (totalPackages == 0) totalPackages = 1; int weight2 = weight / totalPackages; int height2 = height / totalPackages; int width2 = width / totalPackages; int length2 = length / totalPackages; if (weight2 < 1) weight2 = 1; if (height2 < 1) height2 = 1; if (width2 < 1) width2 = 1; if (length2 < 1) length2 = 1; //Altura não pode ser maior que o comprimento, para evitar erro, igualamos e a embalagem deve ser adaptada. if (height2 > width2) width2 = height2; Debug.WriteLine("Plugin.Shipping.Correios: Multiplos pacotes"); correiosCalculation.Pacotes.Add(new CorreiosBatchCalculation.Pacote() { Altura = height2, Comprimento = length2, Largura = width2, Diametro = 0, FormatoPacote = true, Peso = weight2, ValorDeclarado = (_correiosSettings.IncluirValorDeclarado ? subtotalBase / totalPackages : 0) }); var result = correiosCalculation.Calculate(); if (result != null) { foreach (cServico s in result.Servicos) { if (s.Erro == "0") { s.Valor = (decimal.Parse(s.Valor, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); s.ValorAvisoRecebimento = (decimal.Parse(s.ValorAvisoRecebimento, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); s.ValorMaoPropria = (decimal.Parse(s.ValorMaoPropria, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); s.ValorValorDeclarado = (decimal.Parse(s.ValorValorDeclarado, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); } } } return result; } }
private cResultado ProcessShipping(GetShippingOptionRequest getShippingOptionRequest, GetShippingOptionResponse getShippingOptionResponse) { var usedMeasureWeight = _measureService.GetMeasureWeightBySystemKeyword(MEASURE_WEIGHT_SYSTEM_KEYWORD); if (usedMeasureWeight == null) { string e = string.Format("Plugin.Shipping.Correios: Could not load \"{0}\" measure weight", MEASURE_WEIGHT_SYSTEM_KEYWORD); _logger.Fatal(e); throw new NopException(e); } var usedMeasureDimension = _measureService.GetMeasureDimensionBySystemKeyword(MEASURE_DIMENSION_SYSTEM_KEYWORD); if (usedMeasureDimension == null) { string e = string.Format("Plugin.Shipping.Correios: Could not load \"{0}\" measure dimension", MEASURE_DIMENSION_SYSTEM_KEYWORD); _logger.Fatal(e); throw new NopException(e); } //Na versão 2.2 o getShippingOptionRequest.ZipPostalCodeFrom retorna string.Empty, possui um TODO... string cepOrigem = null; if (this._shippingSettings.ShippingOriginAddressId > 0) { var addr = this._addressService.GetAddressById(this._shippingSettings.ShippingOriginAddressId); if (addr != null && !String.IsNullOrEmpty(addr.ZipPostalCode) && addr.ZipPostalCode.Length >= 8 && addr.ZipPostalCode.Length <= 9) { cepOrigem = addr.ZipPostalCode; } } if (cepOrigem == null) { _logger.Fatal("Plugin.Shipping.Correios: CEP de Envio em branco ou inválido, configure nas opções de envio do NopCommerce.Em Administração > Configurações > Configurações de Envio. Formato: 00000000"); throw new NopException("Plugin.Shipping.Correios: CEP de Envio em branco ou inválido, configure nas opções de envio do NopCommerce.Em Administração > Configurações > Configurações de Envio. Formato: 00000000"); } var correiosCalculation = new CorreiosBatchCalculation(this._logger) { CodigoEmpresa = _correiosSettings.CodigoEmpresa, Senha = _correiosSettings.Senha, CepOrigem = cepOrigem, Servicos = _correiosSettings.CarrierServicesOffered, AvisoRecebimento = _correiosSettings.IncluirAvisoRecebimento, MaoPropria = _correiosSettings.IncluirMaoPropria, CepDestino = getShippingOptionRequest.ShippingAddress.ZipPostalCode }; decimal subtotalBase = decimal.Zero; decimal orderSubTotalDiscountAmount = decimal.Zero; Discount orderSubTotalAppliedDiscount = null; decimal subTotalWithoutDiscountBase = decimal.Zero; decimal subTotalWithDiscountBase = decimal.Zero; _orderTotalCalculationService.GetShoppingCartSubTotal(getShippingOptionRequest.Items, out orderSubTotalDiscountAmount, out orderSubTotalAppliedDiscount, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase); subtotalBase = subTotalWithDiscountBase; int length = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(getShippingOptionRequest.GetTotalLength(), usedMeasureDimension)) / 10); int height = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(getShippingOptionRequest.GetTotalHeight(), usedMeasureDimension)) / 10); int width = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(getShippingOptionRequest.GetTotalWidth(), usedMeasureDimension)) / 10); int weight = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureWeight(_shippingService.GetShoppingCartTotalWeight(getShippingOptionRequest.Items), usedMeasureWeight))); if (length < 1) { length = 1; } if (height < 1) { height = 1; } if (width < 1) { width = 1; } if (weight < 1) { weight = 1; } //Altura não pode ser maior que o comprimento, para evitar erro, igualamos e a embalagem deve ser adaptada. if (height > length) { length = height; } if (IsPackageTooSmall(length, height, width)) { length = MIN_PACKAGE_LENGTH; height = MIN_PACKAGE_HEIGHT; width = MIN_PACKAGE_WIDTH; } if ((!IsPackageTooHeavy(weight)) && (!IsPackageTooLarge(length, height, width))) { Debug.WriteLine("Plugin.Shipping.Correios: Pacote unico"); correiosCalculation.Pacotes.Add(new CorreiosBatchCalculation.Pacote() { Altura = height, Comprimento = length, Largura = width, Diametro = 0, FormatoPacote = true, Peso = weight, ValorDeclarado = (_correiosSettings.IncluirValorDeclarado ? subtotalBase : 0) }); return(correiosCalculation.Calculate()); } else { int totalPackages = 1; int totalPackagesDims = 1; int totalPackagesWeights = 1; if (IsPackageTooHeavy(weight)) { totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)weight / (decimal)MAX_PACKAGE_WEIGHT)); } if (IsPackageTooLarge(length, height, width)) { totalPackagesDims = Convert.ToInt32(Math.Ceiling((decimal)TotalPackageSize(length, height, width) / (decimal)MAX_PACKAGE_TOTAL_DIMENSION)); } totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights; if (totalPackages == 0) { totalPackages = 1; } int weight2 = weight / totalPackages; int height2 = height / totalPackages; int width2 = width / totalPackages; int length2 = length / totalPackages; if (weight2 < 1) { weight2 = 1; } if (height2 < 1) { height2 = 1; } if (width2 < 1) { width2 = 1; } if (length2 < 1) { length2 = 1; } //Altura não pode ser maior que o comprimento, para evitar erro, igualamos e a embalagem deve ser adaptada. if (height2 > width2) { width2 = height2; } Debug.WriteLine("Plugin.Shipping.Correios: Multiplos pacotes"); correiosCalculation.Pacotes.Add(new CorreiosBatchCalculation.Pacote() { Altura = height2, Comprimento = length2, Largura = width2, Diametro = 0, FormatoPacote = true, Peso = weight2, ValorDeclarado = (_correiosSettings.IncluirValorDeclarado ? subtotalBase / totalPackages : 0) }); var result = correiosCalculation.Calculate(); if (result != null) { foreach (cServico s in result.Servicos) { if (s.Erro == "0") { s.Valor = (decimal.Parse(s.Valor, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); s.ValorAvisoRecebimento = (decimal.Parse(s.ValorAvisoRecebimento, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); s.ValorMaoPropria = (decimal.Parse(s.ValorMaoPropria, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); s.ValorValorDeclarado = (decimal.Parse(s.ValorValorDeclarado, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); } } } return(result); } }
private cResultado ProcessShipping(GetShippingOptionRequest getShippingOptionRequest, GetShippingOptionResponse getShippingOptionResponse) { var usedMeasureWeight = _measureService.GetMeasureWeightBySystemKeyword(MEASURE_WEIGHT_SYSTEM_KEYWORD); if (usedMeasureWeight == null) { string e = string.Format("Plugin.Shipping.Correios: Could not load \"{0}\" measure peso", MEASURE_WEIGHT_SYSTEM_KEYWORD); _logger.Fatal(e); throw new NopException(e); } var usedMeasureDimension = _measureService.GetMeasureDimensionBySystemKeyword(MEASURE_DIMENSION_SYSTEM_KEYWORD); if (usedMeasureDimension == null) { string e = string.Format("Plugin.Shipping.Correios: Could not load \"{0}\" measure dimension", MEASURE_DIMENSION_SYSTEM_KEYWORD); _logger.Fatal(e); throw new NopException(e); } //Na versão 2.2 o getShippingOptionRequest.ZipPostalCodeFrom retorna string.Empty, possui um TODO... string cepOrigem = null; if (this._shippingSettings.ShippingOriginAddressId > 0) { var addr = this._addressService.GetAddressById(this._shippingSettings.ShippingOriginAddressId); if (addr != null && !String.IsNullOrEmpty(addr.ZipPostalCode) && addr.ZipPostalCode.Length >= 8 && addr.ZipPostalCode.Length <= 9) { cepOrigem = addr.ZipPostalCode; } } if (cepOrigem == null) { _logger.Fatal("Plugin.Shipping.Correios: CEP de Envio em branco ou inválido, configure nas opções de envio do NopCommerce.Em Administração > Configurações > Configurações de Envio. Formato: 00000000"); throw new NopException("Plugin.Shipping.Correios: CEP de Envio em branco ou inválido, configure nas opções de envio do NopCommerce.Em Administração > Configurações > Configurações de Envio. Formato: 00000000"); } if (!string.IsNullOrEmpty(_correiosSettings.CEPRestito)) { string CepDestinoRestrito = getShippingOptionRequest.ShippingAddress.ZipPostalCode.Replace("-", "").Replace(".", ""); int[] ints = _correiosSettings.CEPRestito.Split(';').Select(s => int.Parse(s)).ToArray(); bool is_cep_retrict = false; bool is_categoria_retrict = false; bool is_restric = false; string[] categoriasrestritas = _correiosSettings.CategoriasRetritras.Split(';'); // esta na lista de cep restrito if (Enumerable.Range(ints[0], ints[1]).Contains(int.Parse(CepDestinoRestrito))) { is_cep_retrict = true; } // se tiver catergoria, quer dizer que so restringe apenas se houver x categrorais if (!string.IsNullOrEmpty(categoriasrestritas[0]) && is_cep_retrict) { var itens = getShippingOptionRequest.Items.Select(x => x.ShoppingCartItem).ToList(); int _categoria; foreach (var a in itens) { _categoria = a.Product.ProductCategories.Select(p => p.CategoryId).FirstOrDefault(); if (categoriasrestritas.Contains(_categoria.ToString())) { is_categoria_retrict = true; break; } } } is_restric = is_categoria_retrict && is_cep_retrict; if (is_restric) { _logger.Fatal("Plugin.Shipping.Correios: Você contém produtos que não podem ser entregue pelos correios na sua região"); return(null); } //89000000-99000000 } var correiosCalculation = new CorreiosBatchCalculation(this._logger) { CodigoEmpresa = _correiosSettings.CodigoEmpresa, Senha = _correiosSettings.Senha, CepOrigem = cepOrigem, Servicos = _correiosSettings.CarrierServicesOffered, AvisoRecebimento = _correiosSettings.IncluirAvisoRecebimento, MaoPropria = _correiosSettings.IncluirMaoPropria, CepDestino = getShippingOptionRequest.ShippingAddress.ZipPostalCode }; decimal subtotalBase = decimal.Zero; decimal orderSubTotalDiscountAmount = decimal.Zero; List <DiscountForCaching> orderSubTotalAppliedDiscount = null; decimal subTotalWithoutDiscountBase = decimal.Zero; decimal subTotalWithDiscountBase = decimal.Zero; _orderTotalCalculationService.GetShoppingCartSubTotal(getShippingOptionRequest.Items.Select(x => x.ShoppingCartItem).ToList(), false, out orderSubTotalDiscountAmount, out orderSubTotalAppliedDiscount, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase); subtotalBase = subTotalWithDiscountBase; decimal comprimentoTmp, larguraTmp, alturaTmp; _shippingService.GetDimensions(getShippingOptionRequest.Items, out larguraTmp, out comprimentoTmp, out alturaTmp); int comprimento = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(comprimentoTmp, usedMeasureDimension)) / 10); int altura = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(alturaTmp, usedMeasureDimension)) / 10); int largura = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(larguraTmp, usedMeasureDimension)) / 10); int peso = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureWeight(_shippingService.GetTotalWeight(getShippingOptionRequest), usedMeasureWeight))); if (comprimento < 1) { comprimento = 1; } if (altura < 1) { altura = 1; } if (largura < 1) { largura = 1; } if (peso < 1) { peso = 1; } //Altura não pode ser maior que o comprimento, para evitar erro, igualamos e a embalagem deve ser adaptada. if (altura > comprimento) { comprimento = altura; } // string ms = " Antes" + "Altura " + altura.ToString() + " Comprimento " + comprimento.ToString() + " Largura " + largura.ToString() + " Peso " + peso.ToString() ; // _logger.Error(ms); if (IsPackageTooSmall(comprimento, altura, largura)) { comprimento = MININO_COMPRIMENTO_PACOTE; altura = MININO_ALTURA_PACOTE; largura = MININO_LARGURA_PACOTE; } if ((!IsPackageTooHeavy(peso)) && (!IsPackageTooLarge(comprimento, altura, largura))) { Debug.WriteLine("Plugin.Shipping.Correios: Pacote unico"); correiosCalculation.Pacotes.Add(new CorreiosBatchCalculation.Pacote() { Altura = altura, Comprimento = comprimento, Largura = largura, Diametro = 0, FormatoPacote = true, Peso = peso, ValorDeclarado = (_correiosSettings.IncluirValorDeclarado ? subtotalBase : 0) }); return(correiosCalculation.Calculate()); } else { int totalPackages = 1; int totalPackagesDims = 1; int totalPackagesWeights = 1; if (IsPackageTooHeavy(peso)) { totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)peso / (decimal)MAX_PACKAGE_WEIGHT)); } if (IsPackageTooLarge(comprimento, altura, largura)) { totalPackagesDims = Convert.ToInt32(Math.Ceiling((decimal)TotalPackageSize(comprimento, altura, largura) / (decimal)MAX_PACKAGE_TOTAL_DIMENSION)); } totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights; if (totalPackages == 0) { totalPackages = 1; } int weight2 = peso / totalPackages; int height2 = altura / totalPackages; int width2 = largura / totalPackages; int length2 = comprimento / totalPackages; if (weight2 < 1) { weight2 = 1; } if (height2 < 1) { height2 = 1; } if (width2 < 1) { width2 = 1; } if (length2 < 1) { length2 = 1; } //Altura não pode ser maior que o comprimento, para evitar erro, igualamos e a embalagem deve ser adaptada. if (height2 > width2) { width2 = height2; } // Debug.WriteLine("Plugin.Shipping.Correios: Multiplos pacotes"); correiosCalculation.Pacotes.Add(new CorreiosBatchCalculation.Pacote() { Altura = height2, Comprimento = length2, Largura = width2, Diametro = 0, FormatoPacote = true, Peso = weight2, ValorDeclarado = (_correiosSettings.IncluirValorDeclarado ? subtotalBase / totalPackages : 0) }); var result = correiosCalculation.Calculate(); if (result != null) { foreach (cServico s in result.Servicos) { if (s.Erro == "0") { s.Valor = (decimal.Parse(s.Valor, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); s.ValorAvisoRecebimento = (decimal.Parse(s.ValorAvisoRecebimento, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); s.ValorMaoPropria = (decimal.Parse(s.ValorMaoPropria, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); s.ValorValorDeclarado = (decimal.Parse(s.ValorValorDeclarado, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); } } } return(result); } }