Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package br.hering.fulfilmentprocess.services.impl;
- import java.io.PrintWriter;
- import java.io.StringWriter;
- import java.math.BigDecimal;
- import java.math.RoundingMode;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import javax.annotation.Resource;
- import javax.xml.bind.JAXBContext;
- import javax.xml.bind.JAXBElement;
- import javax.xml.bind.JAXBException;
- import javax.xml.bind.Marshaller;
- import org.apache.commons.collections.CollectionUtils;
- import org.apache.commons.lang.StringUtils;
- import org.apache.log4j.Logger;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.ws.client.core.WebServiceTemplate;
- import com.flieger.adyen.service.AdyenPaymentTransactionEntryService;
- import com.flieger.carrier.services.CarrierDeliveryService;
- import com.flieger.carrier.services.CarrierZoneDeliveryModeService;
- import com.flieger.data.NewsletterSubscriberData;
- import com.flieger.facades.NewsletterSubscriberFacade;
- import com.flieger.payment.model.AbstractPaymentInfoModel;
- import com.flieger.payment.model.AdyenCreditCardPaymentInfoModel;
- import com.flieger.payment.model.AdyenDebitPaymentInfoModel;
- import com.flieger.payment.model.BoletoPaymentInfoModel;
- import com.flieger.payment.model.MultiplePaymentInfoModel;
- import br.com.hering.oms.enums.OMSRefundType;
- import br.com.hering.oms.model.ReservePaymentInfoModel;
- import br.hering.core.enums.BankAccountType;
- import br.hering.core.enums.TipoDeEndereco;
- import br.hering.core.model.BankInformationsModel;
- import br.hering.core.model.ExchangeAndReturnProcessModel;
- import br.hering.core.model.ExchangeAndReturnProductsModel;
- import br.hering.core.model.HeringSizeVariantProductModel;
- import br.hering.core.model.order.payment.VoucherPaymentInfoModel;
- import br.hering.fulfilmentprocess.dao.OMSOrderDao;
- import br.hering.fulfilmentprocess.exceptions.AddressMethodException;
- import br.hering.fulfilmentprocess.exceptions.DeliveryModeException;
- import br.hering.fulfilmentprocess.message.order.oms.CancelFulfillment;
- import br.hering.fulfilmentprocess.message.order.oms.Categorias;
- import br.hering.fulfilmentprocess.message.order.oms.Cliente;
- import br.hering.fulfilmentprocess.message.order.oms.CustosDeFrete;
- import br.hering.fulfilmentprocess.message.order.oms.DadosPedido;
- import br.hering.fulfilmentprocess.message.order.oms.Endereco;
- import br.hering.fulfilmentprocess.message.order.oms.ExtensionAttributes;
- import br.hering.fulfilmentprocess.message.order.oms.Fornecimento;
- import br.hering.fulfilmentprocess.message.order.oms.Fornecimentos;
- import br.hering.fulfilmentprocess.message.order.oms.ImportarPedidoRequest;
- import br.hering.fulfilmentprocess.message.order.oms.Item;
- import br.hering.fulfilmentprocess.message.order.oms.Items;
- import br.hering.fulfilmentprocess.message.order.oms.Itens;
- import br.hering.fulfilmentprocess.message.order.oms.Pagamento;
- import br.hering.fulfilmentprocess.message.order.oms.Pedido;
- import br.hering.fulfilmentprocess.message.order.oms.Refund;
- import br.hering.fulfilmentprocess.message.order.oms.RefundAttributes;
- import br.hering.fulfilmentprocess.message.order.oms.Remessa;
- import br.hering.fulfilmentprocess.message.order.oms.Resultado;
- import br.hering.fulfilmentprocess.message.order.oms.ReturnFulfillment;
- import br.hering.fulfilmentprocess.message.order.oms.SendFulfillmentCancellationResponse;
- import br.hering.fulfilmentprocess.message.order.oms.SendFulfillmentReturnResponse;
- import br.hering.fulfilmentprocess.message.order.oms.SendOrderResponse;
- import br.hering.fulfilmentprocess.message.order.oms.Vendedor;
- import br.hering.fulfilmentprocess.services.ExportOMSOrderService;
- import br.hering.fulfilmentprocess.services.impl.DefaultExportOrderService.TipoDePagamento;
- import de.hybris.platform.basecommerce.enums.ConsignmentStatus;
- import de.hybris.platform.category.model.CategoryModel;
- import de.hybris.platform.commerceservices.constants.GeneratedCommerceServicesConstants.Enumerations.CustomerType;
- import de.hybris.platform.commerceservices.product.CommerceProductService;
- import de.hybris.platform.commerceservices.url.UrlResolver;
- import de.hybris.platform.core.enums.Gender;
- import de.hybris.platform.core.model.order.AbstractOrderEntryModel;
- import de.hybris.platform.core.model.order.OrderModel;
- import de.hybris.platform.core.model.order.payment.CreditCardPaymentInfoModel;
- import de.hybris.platform.core.model.order.price.DiscountModel;
- import de.hybris.platform.core.model.product.ProductModel;
- import de.hybris.platform.core.model.user.AddressModel;
- import de.hybris.platform.core.model.user.CustomerModel;
- import de.hybris.platform.ordersplitting.model.ConsignmentEntryModel;
- import de.hybris.platform.ordersplitting.model.ConsignmentModel;
- import de.hybris.platform.payment.enums.PaymentTransactionType;
- import de.hybris.platform.payment.model.PaymentTransactionEntryModel;
- import de.hybris.platform.util.Config;
- import de.hybris.platform.util.DiscountValue;
- import de.hybris.platform.voucher.VoucherService;
- import de.hybris.platform.voucher.model.PromotionVoucherModel;
- import de.hybris.platform.voucher.model.VoucherModel;
- public class DefaultExportOMSOrderService implements ExportOMSOrderService {
- public static enum TipoDePagamento{
- VALE_PRESENTE("VALE PRESENTE", "&", "Vale presente liberado pelo Sac"),
- GIFT_CARD("GIFT CARD", "@", "Recebimento com o Gift Card"),
- CARTAO_DE_CREDITO("CARTAO DE CREDITO", "CREDIT_CARD", "Pagamento com Cartão de Crédito"),
- CARTAO_DE_DEBITO("CARTAO DE DEBITO", "E", "Pagamento com Cartão de Débito"),
- BOLETO("BOLETO", "BOLETO", "Pagamento com Boleto"),
- DEBITO_ONLINE("DEBITO ONLINE", "U", "Pagamento com Debito Online"),
- VALE_CREDITO("VALE CREDITO", "CUSTOMER_CREDIT", "Utilizado em casos de Créditos por devolução"),
- ESTORNO_CARTO_CREDITO("ESTORNO CARTAO DE CREDITO", "X", "Estorno da Compra do Cartão de Crédito"),
- RESERVA("RESERVA", "RESERVE", "Reservar para retirada em loja");
- private final String name;
- private final String code;
- private final String description;
- TipoDePagamento(final String name, final String code, final String description){
- this.name = name;
- this.code = code;
- this.description = description;
- }
- /**
- * @return the name
- */
- public String getName() {
- return name;
- }
- /**
- * @return the code
- */
- public String getCode() {
- return code;
- }
- /**
- * @return the description
- */
- public String getDescription() {
- return description;
- }
- }
- protected final Logger LOG = Logger.getLogger(this.getClass());
- private static final String CLEARSALE = "ClearSale";
- private static final int APROVADO_CLEARSALE = 1;
- private static final String VOUCHER_VALIDATE = "vc_";
- private static final String VOUCHER_DEVOLUTION = "return_";
- private static final String VOUCHER_EXCHANGE = "exchange_";
- private static final String VOUCHER_OLD_EXCHAGE = "old_exchange_";
- private static final String VALE_PRESENTE = "gf";
- private static final String CIELO = "cielo";
- private static final String PENDING = "PENDING";
- private static final String WAITING = "WAITING";
- private static final Map<String, String> STORE_CODE_MAPPING;
- static {
- STORE_CODE_MAPPING = new HashMap<String,String>();
- STORE_CODE_MAPPING.put("hering", "001");
- STORE_CODE_MAPPING.put("dzarm", "002");
- STORE_CODE_MAPPING.put("puc", "003");
- STORE_CODE_MAPPING.put("kids", "004");
- STORE_CODE_MAPPING.put("foryou", "005");
- STORE_CODE_MAPPING.put("outlet", "006");
- }
- @Autowired
- private WebServiceTemplate enviarPedidosWSTemplate;
- @Resource(name = "newsletterSubscriptionFacade")
- private NewsletterSubscriberFacade newsletterSubscriptionFacade;
- @Resource
- CarrierDeliveryService deliveryService;
- @Resource
- private CarrierZoneDeliveryModeService zoneDeliveryModeService;
- @Resource
- private VoucherService voucherService;
- @Resource
- private AdyenPaymentTransactionEntryService paymentTransactionEntryService;
- @Resource
- private CommerceProductService commerceProductService;
- @Resource
- private UrlResolver<ProductModel> productModelUrlResolver;
- private OMSOrderDao omsOrderDao;
- @Override
- public boolean exportOrder(final OrderModel order)
- {
- LOG.info("Iniciando envio do pedido numero:" + order.getCode() + " para o OMS via PI.");
- final DadosPedido omsDadosPedido = new DadosPedido();
- boolean success = this.populateDadosPedido(order, omsDadosPedido);
- final ImportarPedidoRequest request = new ImportarPedidoRequest();
- request.setDadosPedido(omsDadosPedido);
- try
- {
- exportToString(request);
- enviarPedidosWSTemplate.setDefaultUri(Config.getParameter("enviar.pedidos.oms.ws.template"));
- JAXBElement<SendOrderResponse> response = (JAXBElement<SendOrderResponse>) enviarPedidosWSTemplate.marshalSendAndReceive(request);
- LOG.info("RESPOSTA PI");
- LOG.info("RespondeCode: " + response.getValue().getReturn().getResponseCode());
- LOG.info("ResponseMessage: " + response.getValue().getReturn().getResponseMessage());
- LOG.info("ResponseJsonRequest: " + response.getValue().getReturn().getResponseJsonRequest());
- }
- catch(Exception e)
- {
- StringWriter sw = new StringWriter();
- e.printStackTrace(new PrintWriter(sw));
- LOG.error(e.getMessage());
- LOG.error(sw.toString());
- }
- LOG.info("Envio do pedido numero:" + order.getCode() + " Finalizado"
- + (success ? " sem" : " com") + " erros.");
- return success;
- }
- /**
- * @param order
- */
- @Override
- public void exportStatus(OrderModel order) {
- // do nothing
- }
- @Override
- public boolean exportExchangeAndReturn(OrderModel order)
- {
- boolean success = false;
- if (checkIfOrderOldExchange(order))
- {
- return true;
- }
- if (checkIfOrderReturn(order))
- {
- ReturnFulfillment returnFulfilment = new ReturnFulfillment();
- success = populateReturnFulfilmentReturn(order, returnFulfilment);
- sendRequestExchangeReturn(returnFulfilment);
- }
- else if (checkIfOrderExchange(order))
- {
- ReturnFulfillment returnFulfilment = new ReturnFulfillment();
- success = populateReturnFulfilmentExchange(order, returnFulfilment);
- sendRequestExchangeReturn(returnFulfilment);
- } else {
- return true;
- }
- LOG.info("Envio do pedido numero:" + order.getCode() + " Finalizado" );
- return success;
- }
- /**
- * @param returnFulfilment
- */
- private void sendRequestExchangeReturn(ReturnFulfillment returnFulfilment) {
- try
- {
- exportToString(returnFulfilment);
- enviarPedidosWSTemplate.setDefaultUri(Config.getParameter("enviar.troca.devolucao.oms.ws.template"));
- JAXBElement<SendFulfillmentReturnResponse> response = (JAXBElement<SendFulfillmentReturnResponse>) enviarPedidosWSTemplate.marshalSendAndReceive(returnFulfilment);
- LOG.info("RESPOSTA PI");
- LOG.info("RespondeCode: " + response.getValue().getReturn().getResponseCode());
- LOG.info("ResponseMessage: " + response.getValue().getReturn().getResponseMessage());
- LOG.info("ResponseJsonRequest: " + response.getValue().getReturn().getResponseJsonRequest());
- }
- catch(Exception e)
- {
- StringWriter sw = new StringWriter();
- e.printStackTrace(new PrintWriter(sw));
- LOG.error(e.getMessage());
- LOG.error(sw.toString());
- }
- }
- /**
- * @param order
- * @param returnFulfilment
- * @return
- */
- private boolean populateReturnFulfilmentExchange(OrderModel order,
- ReturnFulfillment returnFulfilment) {
- ExchangeAndReturnProcessModel exchangeAndReturnProcess = order.getExchangeAndReturnProcess();
- OrderModel originalOrder = getOmsOrderDao().getOrderByCode(exchangeAndReturnProcess.getOriginalOrderCode());
- String consignmentCode = originalOrder.getConsignments().iterator().next().getOmsFulfillmentId();
- if (consignmentCode == null || StringUtils.isBlank(consignmentCode))
- {
- consignmentCode = "F1";
- }
- returnFulfilment.setClientId(Config.getParameter("hering.omni.oms.clientid"));
- returnFulfilment.setChannelId(order.getStore().getOmsChannel().getCode());
- returnFulfilment.setCancelationReason("OTHER");
- returnFulfilment.setFulfillmentId(consignmentCode);
- returnFulfilment.setOrderId(originalOrder.getCode());
- returnFulfilment.setExceptionId(exchangeAndReturnProcess.getChangedOldProductsOrderCode());
- returnFulfilment.setPlacedAt(convertDate(order.getDate()));
- //ADD OLD_EXCHANGE ORDER CODE (DV01)
- //POPULATE EXTENSION ATTRIBUTES
- ExtensionAttributes extensionAttributes = new ExtensionAttributes();
- extensionAttributes.setHybrisExchangeOrderId(exchangeAndReturnProcess.getChangedOldProductsOrderCode());
- /*extensionAttributes.setHybrisRefundOrderId("null");*/
- extensionAttributes.setReturnText(exchangeAndReturnProcess.getDescription());
- extensionAttributes.setReverseLogisticTrackingCode(exchangeAndReturnProcess.getCodigoAutPostagem());
- Items items = new Items();
- List<Item> itemList = new ArrayList<Item>();
- List<ExtensionAttributes> extensionAttributesList = new ArrayList<ExtensionAttributes>();
- extensionAttributesList.add(extensionAttributes);
- returnFulfilment.getExtensionAttributes().addAll(extensionAttributesList);
- int i = 1;
- for (ExchangeAndReturnProductsModel exchangeReturnProduct : exchangeAndReturnProcess.getChangedProducts())
- {
- Item item = new Item();
- item.setSku(exchangeReturnProduct.getOriginalProduct().getCode());
- item.setQuantity(exchangeReturnProduct.getQuantity().toString());
- item.setStockType("PHYSICAL");
- br.hering.fulfilmentprocess.message.order.oms.Item.ExtensionAttributes itemExtAttributes = new br.hering.fulfilmentprocess.message.order.oms.Item.ExtensionAttributes();
- itemExtAttributes.setHybrisItemSequenceId(String.valueOf(i++));
- itemExtAttributes.setHybrisReferenceOrderId(exchangeAndReturnProcess.getChangedOldProductsOrderCode());
- HeringSizeVariantProductModel heringProduto = (HeringSizeVariantProductModel) exchangeReturnProduct.getOriginalProduct();
- itemExtAttributes.setProductColorId(heringProduto.getBaseProduct().getCode().split("_")[1]);
- itemExtAttributes.setProductId(heringProduto.getBaseProduct().getCode().split("_")[0]);
- itemExtAttributes.setReason(String.valueOf(exchangeReturnProduct.getReason()));
- item.setExtensionAttributes(itemExtAttributes);
- itemList.add(item);
- }
- returnFulfilment.setItems(items);
- returnFulfilment.getItems().getItem().addAll(itemList);
- final DadosPedido omsDadosPedido = new DadosPedido();
- boolean success = this.populateDadosPedido(order, omsDadosPedido);
- final ImportarPedidoRequest request = new ImportarPedidoRequest();
- request.setDadosPedido(omsDadosPedido);
- br.hering.fulfilmentprocess.message.order.oms.Order newOrder = new br.hering.fulfilmentprocess.message.order.oms.Order();
- newOrder.setImportarPedidoRequest(request);
- returnFulfilment.setOrder(newOrder);
- return true;
- }
- private boolean populateReturnFulfilmentReturn(OrderModel order,
- ReturnFulfillment returnFulfilment) {
- ExchangeAndReturnProcessModel exchangeAndReturnProcess = order.getExchangeAndReturnProcess();
- OrderModel originalOrder = getOmsOrderDao().getOrderByCode(exchangeAndReturnProcess.getOriginalOrderCode());
- String fulfillmentCode = originalOrder.getConsignments().iterator().next().getOmsFulfillmentId();
- if (fulfillmentCode == null || StringUtils.isBlank(fulfillmentCode))
- {
- fulfillmentCode = "F1";
- }
- returnFulfilment.setClientId(Config.getParameter("hering.omni.oms.clientid"));
- returnFulfilment.setChannelId(order.getStore().getOmsChannel().getCode());
- returnFulfilment.setCancelationReason("OTHER");
- returnFulfilment.setFulfillmentId(fulfillmentCode);
- returnFulfilment.setOrderId(originalOrder.getCode());
- returnFulfilment.setExceptionId(order.getCode());
- returnFulfilment.setPlacedAt(convertDate(order.getDate()));
- //ADD RETURN ORDER CODE (DV01)
- //POPULATE EXTENSION ATTRIBUTES
- ExtensionAttributes extensionAttributes = new ExtensionAttributes();
- /*extensionAttributes.setHybrisExchangeOrderId("null");*/
- extensionAttributes.setHybrisRefundOrderId(order.getCode());
- extensionAttributes.setReturnText(exchangeAndReturnProcess.getDescription());
- extensionAttributes.setReverseLogisticTrackingCode(exchangeAndReturnProcess.getCodigoAutPostagem());
- List<ExtensionAttributes> extensionAttributesList = new ArrayList<ExtensionAttributes>();
- extensionAttributesList.add(extensionAttributes);
- returnFulfilment.getExtensionAttributes().addAll(extensionAttributesList);
- Items items = new Items();
- List<Item> itemList = new ArrayList<Item>();
- int i = 1;
- for (ExchangeAndReturnProductsModel exchangeReturnProduct : exchangeAndReturnProcess.getReturnProducts())
- {
- Item item = new Item();
- item.setSku(exchangeReturnProduct.getOriginalProduct().getCode());
- item.setQuantity(exchangeReturnProduct.getQuantity().toString());
- item.setStockType("PHYSICAL");
- br.hering.fulfilmentprocess.message.order.oms.Item.ExtensionAttributes itemExtAttributes = new br.hering.fulfilmentprocess.message.order.oms.Item.ExtensionAttributes();
- itemExtAttributes.setHybrisItemSequenceId(String.valueOf(i++));
- itemExtAttributes.setHybrisReferenceOrderId(order.getCode());
- HeringSizeVariantProductModel heringProduto = (HeringSizeVariantProductModel) exchangeReturnProduct.getOriginalProduct();
- itemExtAttributes.setProductColorId(heringProduto.getBaseProduct().getCode().split("_")[1]);
- itemExtAttributes.setProductId(heringProduto.getBaseProduct().getCode().split("_")[0]);
- itemExtAttributes.setReason(String.valueOf(exchangeReturnProduct.getReason()));
- item.setExtensionAttributes(itemExtAttributes);
- itemList.add(item);
- }
- returnFulfilment.setItems(items);
- returnFulfilment.getItems().getItem().addAll(itemList);
- Refund refund = new Refund();
- refund.setRefundValue(String.valueOf(exchangeAndReturnProcess.getTotalValueReturned()));
- RefundAttributes atts = new RefundAttributes();
- if (exchangeAndReturnProcess.getBankInformation() != null)
- {
- BankInformationsModel bankInfo = exchangeAndReturnProcess.getBankInformation();
- refund.setRefundType(OMSRefundType.OFFLINE_REFUND.getCode());
- if (exchangeAndReturnProcess.getBankInformation().getOperation().equals("Corrente"))
- {
- atts.setBankAccountType("conta-corrente");
- }
- else
- {
- atts.setBankAccountType("conta-poupança");
- }
- atts.setBankCode(bankInfo.getBank());
- atts.setBankBranch(bankInfo.getAgency());
- if(bankInfo.getAgency().contains("-"))
- {
- atts.setBankBranch(bankInfo.getAgency().split("-")[0]);
- atts.setBankBranchCheckDigit(bankInfo.getAgency().split("-")[1]);
- } else {
- atts.setBankBranch(bankInfo.getAgency());
- }
- if(bankInfo.getAccount().contains("-"))
- {
- atts.setBankAccount(bankInfo.getAccount().split("-")[0]);
- atts.setBankAccountCheckDigit(bankInfo.getAccount().split("-")[1]);
- } else {
- atts.setBankAccount(bankInfo.getAccount());
- }
- atts.setCustomerDocumentNumber(bankInfo.getDocument());
- atts.setCustomerName(bankInfo.getAccountHolder());
- }
- else if (exchangeAndReturnProcess.getIsCreditNote() != null && exchangeAndReturnProcess.getIsCreditNote())
- {
- refund.setRefundType(OMSRefundType.GIFTCARD.getCode());
- } else {
- refund.setRefundType(OMSRefundType.PAYMENT_VOID.getCode());
- }
- refund.setRefundAttributes(atts);
- returnFulfilment.setRefund(refund);
- return true;
- }
- private String getOriginalExchangedProductSku(OrderModel order, String newProductSku) {
- ExchangeAndReturnProcessModel exchangeAndReturnProcess = order.getExchangeAndReturnProcess();
- for (ExchangeAndReturnProductsModel exchangeReturnProduct : exchangeAndReturnProcess.getChangedProducts())
- {
- if (exchangeReturnProduct.getChangedProduct() != null && newProductSku.equals(exchangeReturnProduct.getChangedProduct().getCode())) {
- return exchangeReturnProduct.getOriginalProduct().getCode();
- }
- }
- return StringUtils.EMPTY;
- }
- private boolean checkIfOrderOldExchange(OrderModel order)
- {
- for (DiscountModel discount : order.getDiscounts())
- {
- if (discount.getCode().contains("OLD_EXCHANGE"))
- {
- return true;
- }
- }
- return false;
- }
- private boolean checkIfOrderExchange(OrderModel order)
- {
- for (DiscountModel discount : order.getDiscounts())
- {
- if (discount.getCode().contains("EXCHANGE"))
- {
- return true;
- }
- }
- return false;
- }
- private boolean checkIfOrderReturn(OrderModel order)
- {
- for (DiscountModel discount : order.getDiscounts())
- {
- if (discount.getCode().contains("RETURN"))
- {
- return true;
- }
- }
- return false;
- }
- @Override
- public boolean exportCancelOrRefund(OrderModel order)
- {
- boolean success = true;
- for (ConsignmentModel consignment : order.getConsignments())
- {
- if (consignment.getStatus().equals(ConsignmentStatus.CANCELLING))
- {
- success = exportCancelOrRefund(order, consignment);
- }
- }
- return success;
- }
- private boolean exportCancelOrRefund(OrderModel order, ConsignmentModel consignment)
- {
- LOG.info("Iniciando envio do pedido numero:" + order.getCode() + " para o OMS via PI.");
- CancelFulfillment cancelFulfilment = new CancelFulfillment();
- populateCancelFulfilment(order, consignment, cancelFulfilment);
- try
- {
- exportToString(cancelFulfilment);
- enviarPedidosWSTemplate.setDefaultUri(Config.getParameter("enviar.pedidos.pendentes"));
- JAXBContext context = JAXBContext.newInstance(CancelFulfillment.class);
- Marshaller m = context.createMarshaller();
- m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- m.marshal(cancelFulfilment, System.out);
- JAXBElement<SendFulfillmentCancellationResponse> response = (JAXBElement<SendFulfillmentCancellationResponse>) enviarPedidosWSTemplate.marshalSendAndReceive(cancelFulfilment);
- LOG.info("RESPOSTA PI");
- LOG.info("RespondeCode: " + response.getValue().getReturn().getResponseCode());
- LOG.info("ResponseMessage: " + response.getValue().getReturn().getResponseMessage());
- LOG.info("ResponseJsonRequest: " + response.getValue().getReturn().getResponseJsonRequest());
- }
- catch(Exception e)
- {
- StringWriter sw = new StringWriter();
- e.printStackTrace(new PrintWriter(sw));
- LOG.error(e.getMessage());
- LOG.error(sw.toString());
- }
- LOG.info("Envio do pedido numero:" + order.getCode() + " Finalizado" );
- return true;
- }
- /**
- * @param order
- * @param consignment
- * @param cancelFulfilment
- */
- private void populateCancelFulfilment(OrderModel order,
- ConsignmentModel consignment, CancelFulfillment cancelFulfilment) {
- Items items = new Items();
- List<Item> itemList = new ArrayList<Item>();
- cancelFulfilment.setClientId(Config.getParameter("hering.omni.oms.clientid"));
- cancelFulfilment.setChannelId(order.getStore().getOmsChannel().getCode());
- cancelFulfilment.setCancelationReason("OTHER");
- cancelFulfilment.setFulfillmentId(consignment.getOmsFulfillmentId());
- cancelFulfilment.setOrderId(consignment.getOrder().getCode());
- cancelFulfilment.setExceptionId(consignment.getOrder().getCode());
- for (ConsignmentEntryModel entry : consignment.getConsignmentEntries())
- {
- Item item = new Item();
- item.setSku(entry.getOrderEntry().getProduct().getCode());
- item.setQuantity(entry.getQuantity().toString());
- item.setStockType("PHYSICAL");
- itemList.add(item);
- }
- cancelFulfilment.setItems(items);
- cancelFulfilment.getItems().getItem().addAll(itemList);
- if (consignment.getOrderFromCancellation() != null)
- {
- final DadosPedido omsDadosPedido = new DadosPedido();
- OrderModel orderModel = (OrderModel) consignment.getOrderFromCancellation();
- cancelFulfilment.setPlacedAt(convertDate(orderModel.getDate()));
- boolean success = this.populateDadosPedido(orderModel, omsDadosPedido);
- final ImportarPedidoRequest request = new ImportarPedidoRequest();
- request.setDadosPedido(omsDadosPedido);
- br.hering.fulfilmentprocess.message.order.oms.Order newOrder = new br.hering.fulfilmentprocess.message.order.oms.Order();
- newOrder.setImportarPedidoRequest(request);
- cancelFulfilment.setOrder(newOrder);
- } else if (consignment.getRefund() != null) {
- Refund refund = new Refund();
- refund.setRefundValue(String.valueOf(consignment.getRefund().getValue()));
- refund.setRefundType(consignment.getRefund().getType().getCode());
- RefundAttributes atts = new RefundAttributes();
- cancelFulfilment.setPlacedAt(convertDate(consignment.getRefund().getCreationtime()));
- if (consignment.getRefund().getType().equals(OMSRefundType.OFFLINE_REFUND))
- {
- if (consignment.getRefund().getBankAccountType().equals(BankAccountType.CHECKING_ACCOUNT)) {
- atts.setBankAccountType("conta-corrente");
- } else {
- atts.setBankAccountType("conta-poupança");
- }
- atts.setBankCode(consignment.getRefund().getBankCode());
- atts.setBankBranch(consignment.getRefund().getBankAgency());
- if (StringUtils.isNotEmpty(consignment.getRefund().getBankAgencyDigit())) {
- atts.setBankBranchCheckDigit(consignment.getRefund().getBankAgencyDigit());
- }
- atts.setBankAccount(consignment.getRefund().getBankAccount());
- if (StringUtils.isNotEmpty(consignment.getRefund().getBankAccountDigit())) {
- atts.setBankAccountCheckDigit(consignment.getRefund().getBankAccountDigit());
- }
- atts.setCustomerName(consignment.getRefund().getName());
- atts.setCustomerDocumentNumber(consignment.getRefund().getDocumentNumber());
- }
- refund.setRefundAttributes(atts);
- cancelFulfilment.setRefund(refund);
- }
- }
- protected String exportToString(final ImportarPedidoRequest integrationDTO) throws JAXBException
- {
- final JAXBContext jaxbContext = JAXBContext.newInstance(ImportarPedidoRequest.class);
- final Marshaller marshaller = jaxbContext.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
- marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
- final StringWriter stringWriter = new StringWriter();
- marshaller.marshal(integrationDTO, stringWriter);
- LOG.info("XML Generated: " + stringWriter.toString());
- return stringWriter.toString();
- }
- protected String exportToString(final CancelFulfillment integrationDTO) throws JAXBException
- {
- final JAXBContext jaxbContext = JAXBContext.newInstance(CancelFulfillment.class);
- final Marshaller marshaller = jaxbContext.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
- marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
- final StringWriter stringWriter = new StringWriter();
- marshaller.marshal(integrationDTO, stringWriter);
- LOG.info("XML Generated: " + stringWriter.toString());
- return stringWriter.toString();
- }
- protected String exportToString(final ReturnFulfillment integrationDTO) throws JAXBException
- {
- final JAXBContext jaxbContext = JAXBContext.newInstance(ReturnFulfillment.class);
- final Marshaller marshaller = jaxbContext.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
- marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
- final StringWriter stringWriter = new StringWriter();
- marshaller.marshal(integrationDTO, stringWriter);
- LOG.info("XML Generated: " + stringWriter.toString());
- return stringWriter.toString();
- }
- private boolean populateDadosPedido(final OrderModel order, final DadosPedido dadosPedido)
- {
- final String siteId = getSiteId(order.getSite().getUid());
- boolean success = buildCustomerData(order, dadosPedido, siteId);
- success &= buildOrderData(order, dadosPedido, siteId);
- buildCarrierData(order, dadosPedido);
- success &= buildPaymentData(order, dadosPedido, siteId);
- buildOrderEntriesData(order, dadosPedido, siteId);
- buildPaymentVoucher(order, dadosPedido, siteId);
- success &= validateDadosPedido(dadosPedido);
- //buildPaymentExchangeAndReturn(order, dadosPedido, siteId);
- buildFulfillments(order, dadosPedido, siteId);
- buildVendedor(order, dadosPedido, siteId);
- adjustPaymentsNumber(dadosPedido);
- if(isDevolutionOrder(order))
- {
- dadosPedido.setResultado(setUpResultado(order, dadosPedido.getPedido(), siteId));
- }
- return success;
- }
- private void buildVendedor(OrderModel order, DadosPedido dadosPedido, String siteId) {
- Vendedor vendedor = new Vendedor();
- vendedor.setCodigoVendedor("NET");
- vendedor.setIdVendedor("1");
- vendedor.setTipoVendedor("1");
- dadosPedido.setVendedor(vendedor);
- }
- private boolean isDevolutionOrder(final OrderModel orderModel)
- {
- try
- {
- Collection<String> vouchersApplied = voucherService
- .getAppliedVoucherCodes(orderModel);
- if(CollectionUtils.isNotEmpty(vouchersApplied))
- {
- String voucherCode =vouchersApplied.iterator().next();
- if(voucherCode.contains(VOUCHER_DEVOLUTION.toUpperCase())
- && orderModel.getExchangeAndReturnProcess() != null
- && orderModel.getExchangeAndReturnProcess().getBankInformation() != null)
- {
- return true;
- }
- }
- return false;
- }
- catch(Exception e)
- {
- LOG.error("Fail on get exchange and return "
- + "type order number:" + orderModel.getCode());
- }
- return false;
- }
- private boolean validateDadosPedido(final DadosPedido dadosPedido)
- {
- return !dadosPedido.getPagamento().isEmpty();
- }
- private String getSiteId(String site)
- {
- if (STORE_CODE_MAPPING.containsKey(site))
- {
- return STORE_CODE_MAPPING.get(site);
- }
- return "";
- }
- private String convertDate(Date date) {
- SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
- return dateFormat.format(date);
- }
- private String convertDateInUSFormat(String dateInString) {
- String formattedDate = null;
- SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
- try {
- Date date = formatter.parse(dateInString);
- formattedDate = convertDate(date);
- } catch (ParseException e) {
- //e.printStackTrace();
- }
- return formattedDate;
- }
- /**
- * @param order
- * @param dadosPedido
- */
- private boolean buildCustomerData(
- final OrderModel order,
- final DadosPedido dadosPedido,
- final String siteId)
- {
- boolean success = true;
- try
- {
- final CustomerModel customer = (CustomerModel) order.getUser();
- final Cliente cliente = new Cliente();
- cliente.setCodigoSite(siteId);
- cliente.setCodigoCliente(customer.getPk().toString());
- if (customer.getType() != null && customer.getType().equals(CustomerType.GUEST))
- {
- String name = "";
- if (order.getDeliveryAddress() != null && order.getDeliveryAddress().getOriginal() != null)
- {
- name += StringUtils.isBlank(order.getDeliveryAddress().getOriginal().getFirstname()) ? "" : order
- .getDeliveryAddress().getOriginal().getFirstname();
- name += " "
- + (StringUtils.isBlank(order.getDeliveryAddress().getOriginal().getLastname()) ? "" : order
- .getDeliveryAddress().getOriginal().getLastname());
- }
- cliente.setNome(name.trim());
- }
- else
- {
- cliente.setNome(customer.getName());
- }
- cliente.setPfPj(customer.getCpfcnpj().length() == 11 ? true : false);
- cliente.setRgIe(customer.getRgIe());
- cliente.setCpfCgc(customer.getCpfcnpj());
- if (customer.getBirthday() != null)
- {
- cliente.setAniversario(convertDate(customer.getBirthday()));
- }
- cliente.setDataCadastramento(convertDate(customer.getCreationtime()));
- if (customer.getGender() != null)
- {
- cliente.setSexo(customer.getGender().getCode().charAt(0) + "");
- }
- else
- {
- cliente.setSexo(Gender.UNDEFINED.getCode().charAt(0) + "");
- }
- if (customer.getDefaultShipmentAddress() != null)
- {
- if (customer.getDefaultShipmentAddress().getDddPhone() != null)
- {
- cliente.setDdd(customer.getDefaultShipmentAddress().getDddPhone());
- }
- if (customer.getDefaultShipmentAddress().getPhone1() != null)
- {
- cliente.setTelefone(customer.getDefaultShipmentAddress().getPhone1());
- }
- }
- cliente.setEmail(customer.getUid().replaceAll("[a-z0-9\\-]*\\|", ""));
- try
- {
- final NewsletterSubscriberData newsLetter = newsletterSubscriptionFacade.findByEmail(customer.getUid().replaceAll(
- "[a-z0-9\\-]*\\|", ""));
- cliente.setNewsletter(newsLetter != null && Boolean.TRUE.equals(newsLetter.getReceive()));
- }
- catch (final Exception e)
- {
- LOG.error("Not FATAL error", e);
- }
- dadosPedido.setCliente(cliente);
- success = buildCustomerAddressData(dadosPedido, customer, order);
- }
- catch (final Exception e)
- {
- success = false;
- LOG.info("Error creating customerData for Order: " + order.getCode() + "; Exception: " + e);
- }
- return success;
- }
- /**
- * @param dadosPedido
- * @param customer
- */
- private boolean buildCustomerAddressData(final DadosPedido dadosPedido,
- final CustomerModel customer, final OrderModel order) {
- boolean success = true;
- if (!isPickup(order)) {
- final Endereco deliveryAddress =
- buildAddress(order.getDeliveryAddress(), customer.getPk().toString());
- if(deliveryAddress == null)
- {
- success = false;
- LOG.info("Error creating deliveryAddress for order: " + order.getCode());
- }
- else if(!dadosPedido.getEndereco().contains(deliveryAddress))
- {
- dadosPedido.getEndereco().add(deliveryAddress);
- }
- }
- Endereco billingAddress = null;
- if (!isReserve(order)) {
- billingAddress =
- buildAddress(order.getPaymentInfo().getBillingAddress(), customer.getPk().toString());
- billingAddress.setEnderecoCobranca(true);
- }
- if(billingAddress == null) {
- if (isReserve(order)) {
- // mesmo quando é reserva, o erp precisa de um endereço de cobrança
- // tentamos de todas sa formas setar esse endereço
- AddressModel userAddress = null;
- if (customer.getDefaultPaymentAddress() != null) {
- userAddress = customer.getDefaultPaymentAddress();
- } else if (customer.getDefaultShipmentAddress() != null){
- userAddress = customer.getDefaultPaymentAddress();
- } else if (customer.getAddresses() != null && customer.getAddresses().size() > 0){
- userAddress = customer.getAddresses().iterator().next();
- }
- if (userAddress == null) {
- success = false;
- LOG.info("Error creating billingAddress for order: " + order.getCode());
- } else {
- billingAddress =
- buildAddress(userAddress, customer.getPk().toString());
- billingAddress.setEnderecoCobranca(true);
- if (!dadosPedido.getEndereco().contains(billingAddress)) {
- dadosPedido.getEndereco().add(billingAddress);
- } else {
- dadosPedido.getEndereco().get(0).setEnderecoCobranca(true);
- }
- }
- }
- } else {
- int indexOf = dadosPedido.getEndereco().indexOf(billingAddress);
- if (indexOf < 0) {
- dadosPedido.getEndereco().add(billingAddress);
- } else {
- dadosPedido.getEndereco().get(indexOf).setEnderecoCobranca(true);
- }
- }
- return success;
- }
- private Endereco buildAddress(final AddressModel add, String codigoCliente)
- {
- try
- {
- final Endereco endereco = new Endereco();
- if(add.getOriginal() != null)
- {
- endereco.setCodigoEndereco(add.getOriginal().getPk().getLongValueAsString());
- }
- else
- {
- endereco.setCodigoEndereco(add.getPk().getLongValueAsString());
- }
- endereco.setDescricaoEndereco(add.getFirstname() + " " + add.getLastname());
- endereco.setPais(add.getCountry().getIsocode());
- endereco.setCep(add.getPostalcode());
- endereco.setBairro(add.getDistrict());
- endereco.setCidade(add.getTown());
- endereco.setComplemento(add.getComplemento());
- endereco.setNumero(add.getStreetnumber());
- endereco.setLogradouro(add.getStreetname());
- endereco.setUf(add.getRegion().getIsocode().substring(3));
- endereco.setEnderecoPrincipal(true);
- endereco.setTipoEndereco(getAddressType(add));
- endereco.setDdd(add.getDddPhone());
- endereco.setTelefone(add.getPhone1());
- endereco.setDddCelular(StringUtils.isEmpty(add.getDddCellPhone()) ? add.getDddPhone() : add.getDddCellPhone());
- endereco.setCelular(StringUtils.isEmpty(add.getCellphone()) ? add.getPhone1() : add.getCellphone());
- endereco.setCodigoCliente(codigoCliente);
- endereco.setEnderecoCobranca(add.getBillingAddress());
- endereco.setEnderecoEntrega(add.getShippingAddress());
- endereco.setCodigoMunicipioIBGE("9999999");
- return endereco;
- }
- catch (Exception e)
- {
- LOG.info("Error creating Address for order export. Customer: "
- + codigoCliente + "; address: " + add.getPk().toString() + "; Exception: " + e);
- }
- return null;
- }
- /**
- * @param order
- * @param DATE_FORMAT
- * @param dadosPedido
- */
- private boolean buildOrderData(final OrderModel order,
- final DadosPedido dadosPedido, String siteId)
- {
- boolean success = true;
- try
- {
- final Pedido pedido = new Pedido();
- pedido.setCodigoSite(siteId);
- // TODO:
- pedido.setClienteId(Config.getParameter("hering.omni.oms.clientid"));
- pedido.setCanalId(order.getStore().getOmsChannel().getCode());
- pedido.setStatus(getOrderStatus(order));
- /*
- *
- * 1: PEDIDO NORMAL
- * 2: PEDIRO RESERVA
- * 3: CARTAO PRESENTE
- * 4: PEDIDO DE TROCA
- * 5: EMBRULHAR PRE PRESENTE
- * */
- if(order.isExchangeOrReturnOrder())
- {
- DiscountModel voucher = voucherService.getAppliedVouchers(order).iterator().next();
- //order.setTotalPrice(voucher.getValue());
- if(voucher.getCode().toLowerCase().contains(VOUCHER_DEVOLUTION) || voucher.getCode().toLowerCase().contains(VOUCHER_OLD_EXCHAGE))
- {
- order.setCode("DV01_"+order.getCode());
- if(order != null && order.getExchangeAndReturnProcess() != null
- && order.getExchangeAndReturnProcess().getDescription() != null){
- pedido.setMensagemCartao(order.getExchangeAndReturnProcess().getDescription());
- }
- pedido.setTipo("4");
- }
- else
- {
- pedido.setTipo("1");
- }
- }
- else if(order != null && order.getEntries() != null && !order.getEntries().isEmpty()
- && order.getEntries().get(0).getProduct().getCode().startsWith("GIF")){
- pedido.setTipo("3");
- }
- else if(order.isPackageProduct()){
- pedido.setTipo("5");
- }
- else{
- pedido.setTipo("1");
- }
- // vazio por enquanto para não dar problema no OMS
- if (pedido.getMensagemCartao() == null) {
- pedido.setMensagemCartao(" ");
- }
- pedido.setCodigoPedido(order.getCode());
- pedido.setData(convertDate(order.getCreationtime()));
- pedido.setDataHoraFinalizacaoPedido(convertDate(order.getDate()));
- pedido.setValorTotal(BigDecimal.valueOf(order.getTotalPrice()
- .doubleValue()).add(BigDecimal.valueOf(order.getTotalDiscounts())));
- /*
- * Quando ha um voucher de vale cr�dito o valor do desconto � zerado
- * e recalculado o valor total
- */
- pedido.setDesconto(BigDecimal.valueOf(order.getTotalDiscounts()));
- if(order.isExchangeOrReturnOrder())
- {
- DiscountModel voucher = voucherService.getAppliedVouchers(order).iterator().next();
- //O valor tem que ser o da ordem que já foi ajustado
- //order.setTotalPrice(voucher.getValue());
- if(voucher.getCode().contains("RETURN_") || voucher.getCode().contains("OLD_EXCHANGE_"))
- {
- pedido.setCodigoDesconto(order.getCodPostagem());
- }
- }
- else if (CollectionUtils.isNotEmpty(order.getDiscounts())) {
- for(String voucherCode: voucherService.getAppliedVoucherCodes(order)){
- if(StringUtils.isNotBlank(voucherCode) && !voucherCode.startsWith(VOUCHER_VALIDATE) && !voucherCode.startsWith(VALE_PRESENTE) ){
- pedido.setCodigoDesconto(voucherCode);
- break;
- }
- }
- }
- if (pedido.getCodigoDesconto() == null) {
- pedido.setCodigoDesconto(" ");
- }
- pedido.setCodigoCliente(order.getUser().getPk().toString());
- //setting deliveryAddress
- AddressModel deliveryAddress = order.getDeliveryAddress();
- if (order.getDeliveryAddress() == null){
- success = false;
- throw new AddressMethodException("Delivery Address does not exist for order: " + order.getCode());
- }
- if(deliveryAddress.getOriginal() != null){
- deliveryAddress = deliveryAddress.getOriginal();
- }
- Endereco aux = new Endereco();
- aux.setCodigoEndereco(deliveryAddress.getPk().getLongValueAsString());
- if(!dadosPedido.getEndereco().contains(aux)){
- success = false;
- LOG.info("FATAL ERROR. Building OrderData for Order: " + order.getCode()
- + " failed. Customer does not contain the DeliveryAddress assingned for this order. "
- + "The order will be sent to PI, but it will fail to integrate to Linx due to this mismatch");
- }
- pedido.setCodigoEnderecoEntrega(aux.getCodigoEndereco());
- pedido.setCodigoEnderecoCobranca(aux.getCodigoEndereco());
- // vazio por enquanto
- pedido.setIdCampanha(" ");
- dadosPedido.setPedido(pedido);
- } catch (Exception e){
- success = false;
- LOG.error("Error building OrderData for order: " + order.getCode(), e);
- }
- return success;
- }
- //Calcula o valor de desconto quando o valor do frete em porcentagem
- private BigDecimal calculateVoucherAbsoluteValue(final BigDecimal desconto, final BigDecimal total){
- if(desconto != BigDecimal.ZERO){
- final BigDecimal percent = desconto.divide(BigDecimal.valueOf(100));
- final BigDecimal absoluteValue = percent.multiply(total);
- return BigDecimal.valueOf(absoluteValue.floatValue()).setScale(2, BigDecimal.ROUND_HALF_UP);
- }
- return BigDecimal.ZERO;
- }
- /**
- * @param order
- * @param dadosPedido
- * @param pedido
- */
- private void buildOrderEntriesData(final OrderModel order,
- final DadosPedido dadosPedido, String siteId) {
- int count = 0;
- int idx = 1;
- for (final AbstractOrderEntryModel entry : order.getEntries()) {
- count = count + entry.getQuantity().intValue();
- HeringSizeVariantProductModel heringProduto = (HeringSizeVariantProductModel) entry.getProduct();
- final Itens item = new Itens();
- item.setCodigoSite(siteId);
- item.setCodigoPedido(order.getCode());
- item.setCodigoProduto(heringProduto.getBaseProduct().getCode()
- .split("_")[0]);
- item.setCorProduto(heringProduto.getBaseProduct().getCode()
- .split("_")[1]);
- item.setTextoPersonalizado(entry.getCustomText());
- item.setNome(heringProduto.getBaseProduct().getName());
- item.setItem(String.valueOf(idx));
- item.setSku(entry.getProduct().getCode());
- item.setQuantidade(entry.getQuantity().intValue());
- item.setPrecoLiquido(BigDecimal.valueOf(entry.getBasePrice() - calculateDiscount(entry.getDiscountValues()).doubleValue() ));
- item.setDesconto(this.calculateDiscount(entry.getDiscountValues()));
- item.setIndicaBrinde(entry.getGiveAway() ? "1" : "0");
- Double weight = heringProduto.getWeight() * 1000;
- item.setPeso(String.valueOf(weight.intValue()));
- final Collection<CategoryModel> categories = commerceProductService.getSuperCategoriesExceptClassificationClassesForProduct(heringProduto);
- if (!categories.isEmpty()) {
- Categorias categorias = new Categorias();
- List<String> strCategories = new ArrayList<String>();
- for (CategoryModel category : categories) {
- if (category.getName() != null) {
- strCategories.add(category.getName());
- }
- }
- if (!strCategories.isEmpty()) {
- categorias.getCategoria().addAll(strCategories);
- item.setCategorias(categorias);
- }
- }
- // marca, talvez tenha um atributo
- String site = order.getSite().getUid();
- String productUrl = Config.getParameter("website." + site + ".https") + productModelUrlResolver.resolve(heringProduto);
- item.setUrl(productUrl);
- item.setTamanho(heringProduto.getSize());
- item.setCodigoDeBarras(heringProduto.getEan());
- if (heringProduto.getBaseProduct().getPicture() != null) {
- String productImageUrl = heringProduto.getBaseProduct().getPicture().getURL();
- if (StringUtils.isNotEmpty(productImageUrl)) {
- item.setImage(productImageUrl);
- }
- }
- item.setCorDescricao(heringProduto.getColorFullDescription());
- item.setMarca(site);
- if (checkIfOrderExchange(order)) {
- item.setReferenceSkuId(heringProduto.getCode());
- item.setHybrisItemSequenceId(String.valueOf(entry.getEntryNumber()));
- }
- if(order.isExchangeOrReturnOrder())
- {
- Collection<DiscountModel> vouchers = voucherService.getAppliedVouchers(order);
- if( CollectionUtils.isNotEmpty(vouchers) )
- {
- DiscountModel voucher = vouchers.iterator().next();
- if(order.isExchangeOrReturnOrder())
- {
- if(voucher.getCode().startsWith("CODE_EXCHANGE"))
- {
- item.setStatus(0);
- }
- else
- {
- item.setStatus(getProductReasonCode(order, heringProduto.getCode()));
- }
- }
- }
- }
- else
- {
- item.setStatus(0);
- }
- dadosPedido.getItens().add(item);
- idx += 1;
- }
- dadosPedido.getPedido().setQuantidadeTotal(count);
- }
- private int getProductReasonCode(final OrderModel orderModel, final String productCode)
- {
- Collection<ExchangeAndReturnProductsModel> exchangeProducts = checkChangedProductListExchange(orderModel);
- if(CollectionUtils.isNotEmpty(exchangeProducts)){
- for(ExchangeAndReturnProductsModel product:exchangeProducts){
- if(product.getOriginalProduct().getCode().equals(productCode)){
- return product.getReason();
- }
- }
- }
- Collection<ExchangeAndReturnProductsModel> returnProducts = checkExchangeProductList(orderModel);
- if(CollectionUtils.isNotEmpty(returnProducts)){
- for(ExchangeAndReturnProductsModel product:returnProducts){
- if(product.getOriginalProduct().getCode().equals(productCode)){
- return product.getReason();
- }
- }
- }
- LOG.warn("Product " + productCode + " without exchange and return reason.");
- return -1;
- }
- /**
- * @param orderModel
- * @return
- */
- private Collection<ExchangeAndReturnProductsModel> checkExchangeProductList(OrderModel orderModel){
- if(orderModel != null && orderModel.getExchangeAndReturnProcess() != null
- && orderModel.getExchangeAndReturnProcess().getReturnProducts() != null){
- return orderModel.getExchangeAndReturnProcess().getReturnProducts();
- }else{
- return null;
- }
- }
- private Collection<ExchangeAndReturnProductsModel> checkChangedProductListExchange(OrderModel orderModel){
- if(orderModel != null && orderModel.getExchangeAndReturnProcess() != null
- && orderModel.getExchangeAndReturnProcess().getChangedProducts() != null){
- return orderModel.getExchangeAndReturnProcess().getChangedProducts();
- }else{
- return null;
- }
- }
- /**
- * @param order
- * @param pedido
- * @throws DeliveryModeException
- */
- private void buildCarrierData(final OrderModel order,
- final DadosPedido dadosPedido) {
- Pedido pedido = dadosPedido.getPedido();
- try{
- pedido.setPeso(BigDecimal.valueOf(deliveryService.calculateTotalWeight(order)));
- pedido.setValorFrete(BigDecimal.valueOf(order.getDeliveryCost().doubleValue()));
- pedido.setPrazoMaximoEntrega(order.getEstimatedDeliveryDays());
- }catch (Exception e) {
- LOG.error("Error building buildCarrierData for order: " + order.getCode(), e);
- }
- }
- private boolean isPickup(final OrderModel order) {
- for (ConsignmentModel consignment : order.getConsignments())
- {
- if (consignment.getOmsFulfillmentType().equals("SHIPMENT")) {
- return false;
- }
- }
- return true;
- }
- private boolean isReserve(final OrderModel order) {
- if (order.getPaymentInfo() instanceof MultiplePaymentInfoModel) {
- final List<AbstractPaymentInfoModel> paymentInfoList =
- ((MultiplePaymentInfoModel) order.getPaymentInfo()).getPaymentInfoList();
- for (int i = 0; i < paymentInfoList.size(); i++)
- {
- final AbstractPaymentInfoModel paymentInfo = paymentInfoList.get(i);
- if(paymentInfo instanceof ReservePaymentInfoModel){
- return true;
- }
- }
- } else if (order.getPaymentInfo() instanceof ReservePaymentInfoModel) {
- return true;
- }
- return false;
- }
- /**
- * @param order
- * @param dadosPedido
- * @param siteId
- * @param success
- */
- private boolean buildPaymentData(
- final OrderModel order,
- final DadosPedido dadosPedido,
- final String siteId)
- {
- if( order.isExchangeOrReturnOrder() )
- {
- return true;
- }
- boolean success = true;
- final List<Pagamento> pagamentoList = new ArrayList<Pagamento>();
- if(!(order.getPaymentInfo() instanceof MultiplePaymentInfoModel))
- {
- buildLegacyPaymentData(order, dadosPedido, siteId);
- return true;
- }
- /**One order can be payed by several methods. The */
- final List<AbstractPaymentInfoModel> paymentInfoList =
- ((MultiplePaymentInfoModel) order.getPaymentInfo()).getPaymentInfoList();
- for ( int i = 0; i < paymentInfoList.size(); i++)
- {
- try
- {
- final AbstractPaymentInfoModel paymentInfo = paymentInfoList.get(i);
- if(paymentInfo instanceof ReservePaymentInfoModel){
- return true;
- }
- final Pagamento pagamento = new Pagamento();
- pagamento.setParcela(i+1);
- pagamento.setCodigoSite(siteId);
- pagamento.setCodigoPedido(order.getCode());
- pagamento.setMoeda(order.getCurrency().getIsocode());
- pagamento.setCapturado(APROVADO_CLEARSALE);
- pagamento.setCodigoAntifraude("APPROVED");
- pagamento.setCotacao(BigDecimal.valueOf(1));
- pagamento.setStatusVerificacaoFraude("APPROVED");
- /**todo o processo de voucher foi unificado no metodo buildVoucherPayment
- * porque o novissimo tipo VoucherPaymentInfo nao tem todas as informacoes necessarias
- * */
- if (paymentInfo instanceof VoucherPaymentInfoModel)
- {
- LOG.info(
- String.format(
- "Found paymentInfo:{code:%s} for order:{code:%s}. This will be handled by the buildPaymentVoucher.",
- paymentInfo.getCode(),
- order.getCode()));
- continue;
- }
- else if (paymentInfo instanceof AdyenDebitPaymentInfoModel )
- {
- final PaymentTransactionEntryModel authorization =
- paymentTransactionEntryService.getForPaymentInfoAndType(
- paymentInfo,
- PaymentTransactionType.AUTHORIZATION3D);
- success &=
- checkIfTransactionIsNull(
- order, paymentInfo, authorization);
- final AdyenDebitPaymentInfoModel debitInfo =
- (AdyenDebitPaymentInfoModel) paymentInfo;
- pagamento.setTipoPagamento(TipoDePagamento.CARTAO_DE_DEBITO.getCode());
- pagamento.setNumeroTitulo(debitInfo.getNumber());
- pagamento.setParcelasCartao(1);
- pagamento.setCodigoAdministradora(
- getCodigoAdminstradoraCartao(
- debitInfo.getSelectedBrand()));
- pagamento.setVencimento(convertDate(order.getDate()));
- // Numero de referencia do adyen
- pagamento.setNumeroAprovacaoCartao(
- authorization.getAdyenAuthorizationCode());
- pagamento.setValor(BigDecimal.valueOf(debitInfo.getValuePaid().doubleValue()));
- pagamento.setValorMoeda(BigDecimal.valueOf(debitInfo.getValuePaid().doubleValue()));
- pagamento.setMetodo(CIELO);
- }
- else
- {
- final PaymentTransactionEntryModel authorization =
- paymentTransactionEntryService.getForPaymentInfoAndType(
- paymentInfo,
- PaymentTransactionType.AUTHORIZATION);
- if (paymentInfo instanceof AdyenCreditCardPaymentInfoModel )
- {
- success &=
- checkIfTransactionIsNull(
- order, paymentInfo, authorization);
- final AdyenCreditCardPaymentInfoModel cc =
- (AdyenCreditCardPaymentInfoModel) paymentInfo;
- pagamento.setTipoPagamento(
- TipoDePagamento.CARTAO_DE_CREDITO.getCode());
- pagamento.setNumeroTitulo(cc.getNumber());
- pagamento.setParcelasCartao((cc.getInstallment() != null
- ? cc.getInstallment() : 0));
- pagamento.setCodigoAdministradora(
- cc.getType().getCode() != null
- ? getCodigoAdminstradoraCartao(cc.getType().getCode())
- : 0);
- pagamento.setVencimento(
- convertDate(order.getDate()));
- if (authorization != null && authorization.getAdyenAuthorizationCode() != null) {
- // Numero de referencia do adyen
- pagamento.setNumeroAprovacaoCartao(authorization.getAdyenAuthorizationCode());
- }
- pagamento.setMetodo(CIELO);
- // this is done in order to send only 2 decimal cases to linx oms
- pagamento.setValor(BigDecimal.valueOf(cc.getValuePaid().doubleValue()));
- pagamento.setValorMoeda(BigDecimal.valueOf(cc.getValuePaid().doubleValue()));
- pagamento.setBandeira(cc.getType().getCode() != null ? cc.getType().getCode() : "");
- }
- else if (paymentInfo instanceof BoletoPaymentInfoModel)
- {
- success &=
- checkIfTransactionIsNull(order, paymentInfo, authorization);
- final BoletoPaymentInfoModel boleto =
- (BoletoPaymentInfoModel) paymentInfo;
- pagamento.setTipoPagamento(TipoDePagamento.BOLETO.getCode());
- pagamento.setNumeroTitulo(
- authorization.getAdyenBoletoNossoNumero());
- pagamento.setParcelasCartao(1);
- // Para boleto o codigo eh ZERO
- pagamento.setCodigoAdministradora(0);
- pagamento.setVencimento(
- convertDateInUSFormat(authorization.getAdyenBoletoExpirationDate()));
- // Campo obrigatorio, fixo numero unico do boleto
- pagamento.setNumeroAprovacaoCartao(
- authorization.getAdyenBoletoNossoNumero());
- final BigDecimal totalPago = BigDecimal.valueOf(order.getTotalPrice());
- pagamento.setValor(totalPago);
- pagamento.setValorMoeda(totalPago);
- //TODO
- pagamento.setCodigoBanco(Config.getParameter("hering.boleto.bank.code"));
- }
- }
- pagamentoList.add(pagamento);
- }
- catch (Exception e)
- {
- success = false;
- LOG.error(
- String.format("Unexpected error for order:{code:%s}",
- order.getCode()), e);
- }
- }
- dadosPedido.getPagamento().addAll(pagamentoList);
- return success;
- }
- private void adjustPaymentsNumber(final DadosPedido pedido) {
- for (int i = 0; i < pedido.getPagamento().size(); i++) {
- Pagamento pagamento = pedido.getPagamento().get(i);
- pagamento.setParcela(i+1);
- }
- }
- private boolean checkIfTransactionIsNull(final OrderModel order,
- final AbstractPaymentInfoModel paymentInfo,
- final PaymentTransactionEntryModel authorization)
- {
- boolean success = true;
- if (authorization == null)
- {
- LOG.error(
- String.format(
- "Authorization for order:{code:%s}; paymentInfo:{code:%s} does not exists",
- order.getCode(), paymentInfo.getCode()));
- success = false;
- }
- return success;
- }
- private String getOrderStatus(final OrderModel order) {
- if (isReserve(order)) {
- return "PROCESSING";
- } else if (hasBoleto(order)) {
- return "PENDING";
- } else {
- return "PROCESSING";
- }
- }
- private String getConsignmentStatus(final OrderModel order) {
- if (isReserve(order)) {
- return "WAITING";
- } else if (hasBoleto(order)) {
- return "PENDING";
- } else {
- return "WAITING";
- }
- }
- private boolean hasBoleto(final OrderModel order) {
- if (order.getPaymentInfo() instanceof MultiplePaymentInfoModel) {
- /**One order can be payed by several methods. The */
- final List<AbstractPaymentInfoModel> paymentInfoList =
- ((MultiplePaymentInfoModel) order.getPaymentInfo()).getPaymentInfoList();
- for ( int i = 0; i < paymentInfoList.size(); i++)
- {
- try
- {
- final AbstractPaymentInfoModel paymentInfo = paymentInfoList.get(i);
- if(paymentInfo instanceof BoletoPaymentInfoModel){
- return true;
- }
- } catch (Exception e) {
- // nothing
- }
- }
- } else if (order.getPaymentInfo() instanceof BoletoPaymentInfoModel) {
- return true;
- }
- return false;
- }
- private Object buildLegacyPaymentData(final OrderModel order,
- final DadosPedido dadosPedido, final String siteId)
- {
- boolean success = true;
- final Pagamento pagamento = new Pagamento();
- pagamento.setCodigoSite(siteId);
- pagamento.setCodigoPedido(order.getCode());
- pagamento.setMoeda(order.getCurrency().getIsocode());
- pagamento.setCapturado(APROVADO_CLEARSALE);
- // pagamento.setCodigoAntifraude(CLEARSALE);
- pagamento.setCodigoAntifraude("APPROVED");
- pagamento.setValor( BigDecimal.valueOf(order.getTotalPrice()) );
- pagamento.setValorMoeda( BigDecimal.valueOf(order.getTotalPrice()) );
- pagamento.setCotacao(BigDecimal.valueOf(1));
- PaymentTransactionEntryModel auth = null;
- if( !CollectionUtils.isEmpty(order.getPaymentTransactions()) ) {
- for (PaymentTransactionEntryModel model : order.getPaymentTransactions().get(0).getEntries())
- {
- if (model.getType().equals(PaymentTransactionType.AUTHORIZATION))
- {
- auth = model;
- break;
- }
- }
- }
- if(order.getPaymentInfo() instanceof ReservePaymentInfoModel){
- return true;
- }
- if ( order.getPaymentInfo() instanceof CreditCardPaymentInfoModel
- && auth != null)
- {
- CreditCardPaymentInfoModel cc =
- (CreditCardPaymentInfoModel) order.getPaymentInfo();
- pagamento.setTipoPagamento(TipoDePagamento.CARTAO_DE_CREDITO.getCode());
- pagamento.setNumeroTitulo(cc.getNumber());
- pagamento.setParcelasCartao(cc.getInstallment());
- pagamento.setCodigoAdministradora(
- getCodigoAdminstradoraCartao(cc.getType().getCode()));
- if(pagamento.getCodigoAdministradora() == 0){
- success = false;
- }
- pagamento.setMetodo(CIELO);
- pagamento.setVencimento(convertDate(order.getDate()));
- // Numero de referencia do adyen
- pagamento.setNumeroAprovacaoCartao(auth.getAdyenAuthorizationCode());
- }
- else if( order.getPaymentInfo() instanceof BoletoPaymentInfoModel
- && auth != null)
- {
- pagamento.setTipoPagamento(TipoDePagamento.BOLETO.getCode());
- pagamento.setNumeroTitulo(auth.getAdyenBoletoNossoNumero());
- pagamento.setParcelasCartao(1);
- // Para boleto o codigo eh ZERO
- pagamento.setCodigoAdministradora(0);
- pagamento.setVencimento(auth.getAdyenBoletoExpirationDate());
- // Campo obrigatorio, fixo numero unico do boleto
- pagamento.setNumeroAprovacaoCartao(auth.getAdyenBoletoNossoNumero());
- //TODO
- pagamento.setCodigoBanco("BANCO");
- }
- else if( order.getPaymentInfo() instanceof VoucherPaymentInfoModel)
- {
- pagamento.setTipoPagamento(TipoDePagamento.VALE_CREDITO.getCode());
- pagamento.setParcelasCartao(1);
- pagamento.setCodigoAdministradora(0);
- pagamento.setVencimento(convertDate(order.getDate()));
- //caso o voucher for igual ao valor da mercadoria n adicionado o metodo de pagamento aqui e sim na buildPaymentVoucher
- if((new Double(0)).equals(order.getTotalPrice())){
- LOG.info("Payment is Voucher and the order totalPrice is equal to 0. "
- + "The payments will be constructed based on the vouchers used by this order");
- return (success && true);
- }
- }
- /*
- * FIXO - utilizado somente quando for utilizado dois tipos de
- * pagamentos diferente para a mesma compra
- */
- pagamento.setParcela(1);
- dadosPedido.getPagamento().add(pagamento);
- return success;
- }
- /*private void buildPaymentExchangeAndReturn( final OrderModel order,
- final DadosPedido dadosPedido, final String siteId)
- {
- final Pagamento pagamento = new Pagamento();
- for(final String voucherCode: voucherService.getAppliedVoucherCodes(order))
- {
- LOG.info("VOUCHER encontrado para ordem "+order.getCode()+"/"+voucherCode);
- if( StringUtils.isNotBlank(voucherCode)
- && ( voucherCode.toLowerCase().contains(VOUCHER_DEVOLUTION)
- || voucherCode.toLowerCase().contains(VOUCHER_EXCHANGE)
- || voucherCode.toLowerCase().contains(VOUCHER_OLD_EXCHAGE)))
- {
- final VoucherModel voucher = voucherService.getVoucher(voucherCode);
- BigDecimal valorDoVoucher = BigDecimal.valueOf(voucher.getValue());
- if(!voucher.getAbsolute()){
- valorDoVoucher = calculateVoucherAbsoluteValue(valorDoVoucher, BigDecimal.valueOf(order.getSubtotal() ));
- }
- BigDecimal total = new BigDecimal(order.getTotalPrice()).setScale(2, RoundingMode.HALF_EVEN);
- if(!voucherCode.toLowerCase().contains(VOUCHER_DEVOLUTION))
- {
- total = new BigDecimal(order.getSubtotal()).setScale(2, RoundingMode.HALF_EVEN);
- }
- //TODO: Ignorar valor retornado acima e utilizar o valor da ordem
- LOG.info(total + " Valor da ordem "+order.getCode());
- LOG.info(dadosPedido.getPagamento().size() + " pagamentos");
- pagamento.setCodigoSite(siteId);
- pagamento.setCodigoPedido(order.getCode());
- pagamento.setMoeda(order.getCurrency().getSymbol());
- pagamento.setCapturado(APROVADO_CLEARSALE);
- pagamento.setCodigoAntifraude(CLEARSALE);
- pagamento.setValor(total);
- pagamento.setValorMoeda(total);
- pagamento.setCotacao(BigDecimal.valueOf(1));
- pagamento.setTipoPagamento(TipoDePagamento.VALE_PRESENTE.getCode());
- pagamento.setParcelasCartao(1);
- pagamento.setCodigoAdministradora(0);
- pagamento.setVencimento(convertDate(order.getDate()));
- pagamento.setParcela(0);
- pagamento.setNumeroTitulo(voucherCode);
- pagamento.setNumeroTitulo(order.getExchangeAndReturnProcess().getOriginalOrderCode());
- pagamento.setTipoPagamento(TipoDePagamento.VALE_CREDITO.getCode());
- if( voucherCode.contains("OLD_EXCHANGE_") || voucherCode.contains("EXCHANGE_") )
- {
- pagamento.setTipoPagamento("V");
- }
- else if( voucherCode.contains("RETURN_") )
- {
- //caso tenha escolhido extorno do cartao
- if( order.getExchangeAndReturnProcess() != null
- && order.getExchangeAndReturnProcess().getVoucher() == null
- && order.getExchangeAndReturnProcess().getBankInformation() == null )
- {
- pagamento.setTipoPagamento("X");
- }
- else if( order.getExchangeAndReturnProcess() != null
- && order.getExchangeAndReturnProcess().getBankInformation() != null )
- {
- pagamento.setTipoPagamento("D");
- }
- else
- {
- pagamento.setTipoPagamento("V");
- pagamento.setNumeroAprovacaoCartao(getValeCredito(order));
- }
- }
- BigDecimal outrosDescontos = BigDecimal.valueOf(order.getSubtotal().doubleValue() - order.getTotalPrice().doubleValue()).setScale(2, RoundingMode.HALF_EVEN);;
- dadosPedido.getPedido().setValorTotal(total);
- dadosPedido.getPedido().setDesconto( outrosDescontos.doubleValue() > 0 ? outrosDescontos : new BigDecimal("0").setScale(2, RoundingMode.HALF_EVEN));
- dadosPedido.getPagamento().add(pagamento);
- }
- }
- LOG.info("Nenhum dado de Pagamento de Troca/Devolução Informado");
- }*/
- private String getValeCredito(OrderModel order) {
- if(order != null && order.getExchangeAndReturnProcess() != null && order.getExchangeAndReturnProcess().getVoucher() != null)
- {
- return ((PromotionVoucherModel) order.getExchangeAndReturnProcess().getVoucher()).getVoucherCode();
- }
- return null;
- }
- private void buildFulfillments(OrderModel order, DadosPedido dadosPedido, String siteId) {
- //TODO: implentar populando com Consignments
- for(ConsignmentModel consignmentModel : order.getConsignments()){
- Fornecimento fornecimento = new Fornecimento();
- fornecimento.setCodigoLocalidade(consignmentModel.getOmsLocationId());
- fornecimento.setCodigoPedido(consignmentModel.getCode().substring(0, consignmentModel.getCode().lastIndexOf("-")));
- fornecimento.setCodigoSite(siteId);
- fornecimento.setId(consignmentModel.getOmsFulfillmentId());
- fornecimento.setStatus(getConsignmentStatus(order));
- fornecimento.setTipo(consignmentModel.getOmsFulfillmentType());
- fornecimento.setShippingAmount(String.valueOf(consignmentModel.getShippingAmount()));
- fornecimento.setReservaId(consignmentModel.getOmsFulfillmentId());
- if (fornecimento.getTipo().equals("PICKUP")) {
- fornecimento.setRetirarEmLojaPrePago(!isReserve(order));
- fornecimento.setBackOfficePagamentoId(!isReserve(order) ? "ADCR" + order.getCode() + consignmentModel.getOmsFulfillmentId() : null);
- }
- for(ConsignmentEntryModel consignmentEntryModel : consignmentModel.getConsignmentEntries()){
- Itens itens = new Itens();
- if(consignmentEntryModel.getOrderEntry() != null){
- itens.setQuantidade(consignmentEntryModel.getOrderEntry().getQuantity().intValue());
- itens.setSku(consignmentEntryModel.getOrderEntry().getProduct().getCode());
- if (consignmentEntryModel.getOrderEntry().getCustomText() == null) {
- itens.setTextoPersonalizado(" ");
- } else {
- itens.setTextoPersonalizado(consignmentEntryModel.getOrderEntry().getCustomText());
- }
- itens.setIndicaBrinde(consignmentEntryModel.getOrderEntry().getGiveAway() ? "1" : "0");
- if (order.getExchangeAndReturnProcess() != null && checkIfOrderExchange(order)) {
- /* TODO */
- itens.setReferenceSkuId(getOriginalExchangedProductSku(order, consignmentEntryModel.getOrderEntry().getProduct().getCode()));
- itens.setHybrisItemSequenceId(String.valueOf(consignmentEntryModel.getOrderEntry().getEntryNumber() + 1));
- }
- }
- fornecimento.getItens().add(itens);
- }
- if(consignmentModel.getShipment() != null){
- Remessa remessa = new Remessa();
- remessa.setCodigoContrato(consignmentModel.getShipment().getContractId());
- remessa.setCodigoTransportadora(consignmentModel.getShipment().getCarrierId());
- remessa.setMetodo(consignmentModel.getShipment().getMethod());
- remessa.setPrecoRemessa(BigDecimal.valueOf(consignmentModel.getShipment().getShippingPrice()));
- remessa.setTempoRemessa(String.valueOf(consignmentModel.getShipment().getShippingTime()));
- if(consignmentModel.getShippingAddress() != null){
- Endereco endereco = new Endereco();
- endereco = buildAddress(consignmentModel.getShippingAddress(), order.getUser().getPk().toString());
- /*endereco.setBairro(consignmentModel.getShippingAddress().getDistrict());
- endereco.setCelular(consignmentModel.getShippingAddress().getCellphone());
- endereco.setCep(consignmentModel.getShippingAddress().getPostalcode());
- endereco.setCidade(consignmentModel.getShippingAddress().getTown());
- endereco.setCodigoCliente(order.getPk().toString());
- endereco.setCodigoEndereco(consignmentModel.getShippingAddress().getPk().toString());
- endereco.setComplemento(consignmentModel.getShippingAddress().getComplemento());
- endereco.setDdd(consignmentModel.getShippingAddress().getDddPhone());
- endereco.setDddCelular(consignmentModel.getShippingAddress().getDddCellPhone());
- endereco.setDescricaoEndereco(consignmentModel.getShippingAddress().getFirstname() + " " + consignmentModel.getShippingAddress().getLastname());
- endereco.setEnderecoCobranca(consignmentModel.getShippingAddress().getBillingAddress());
- endereco.setEnderecoEntrega(consignmentModel.getShippingAddress().getShippingAddress());
- endereco.setEnderecoPrincipal(consignmentModel.getShippingAddress().getContactAddress());
- endereco.setLogradouro(consignmentModel.getShippingAddress().getStreetname());
- endereco.setNumero(consignmentModel.getShippingAddress().getStreetnumber());
- endereco.setPais(consignmentModel.getShippingAddress().getCountry();
- endereco.setTelefone(consignmentModel.getShippingAddress().getPhone1());
- endereco.setTipoEndereco(getAddressType(consignmentModel.getShippingAddress()));
- endereco.setUf(consignmentModel.getShippingAddress().getRegion() != null ?
- consignmentModel.getShippingAddress().getRegion().getIsocode().substring(3) : null);
- endereco.setCodigoMunicipioIBGE("9999999");*/
- remessa.setEndereco(endereco);
- }
- fornecimento.setRemessa(remessa);
- }
- if (consignmentModel.getFreightCosts() != null) {
- CustosDeFrete shippingCost = new CustosDeFrete();
- shippingCost.setEsperandoTempoTransferencia(String.valueOf(consignmentModel.getFreightCosts().getWaitingTransferTime()));
- shippingCost.setPrecoSeparacao(BigDecimal.valueOf(consignmentModel.getFreightCosts().getHandlingPrice()));
- shippingCost.setPrecoTotal(BigDecimal.valueOf(consignmentModel.getFreightCosts().getTotalPrice()));
- shippingCost.setPrecoTransferencia(BigDecimal.valueOf(consignmentModel.getFreightCosts().getTransferPrice()));
- shippingCost.setTempoChegadaEstoque(String.valueOf(consignmentModel.getFreightCosts().getStockArrivalTime()));
- shippingCost.setTempoSeparacao(String.valueOf(consignmentModel.getFreightCosts().getHandlingTime()));
- shippingCost.setTempoTotal(String.valueOf(consignmentModel.getFreightCosts().getTotalTime()));
- shippingCost.setTempoTransferencia(String.valueOf(consignmentModel.getFreightCosts().getTransferTime()));
- fornecimento.setCustosDeFrete(shippingCost);
- }
- dadosPedido.setFornecimentos(new Fornecimentos());
- dadosPedido.getFornecimentos().getFornecimento().add(fornecimento);
- }
- }
- private void buildPaymentVoucher(
- final OrderModel order,
- final DadosPedido dadosPedido, final String siteId)
- {
- final Pagamento pagamento = new Pagamento();
- //apenas um voucher promocional por pedido, mais um voucher tratado pelo buildPayment
- for(final String voucherCode: voucherService.getAppliedVoucherCodes(order))
- {
- LOG.info("Encontrado voucher: " + voucherCode);
- if( StringUtils.isNotBlank(voucherCode)
- && ( voucherCode.toLowerCase().startsWith(VOUCHER_VALIDATE)
- || voucherCode.toLowerCase().startsWith(VALE_PRESENTE)))
- {
- final VoucherModel voucher = voucherService.getVoucher(voucherCode);
- if(voucher == null){
- LOG.info("Voucher eh invalido. Skipping...");
- continue;
- } else {
- LOG.info("Voucher eh valido. Criando pagamento...");
- }
- BigDecimal valorDoVoucher = BigDecimal.valueOf(voucher.getValue());
- if(!voucher.getAbsolute()){
- valorDoVoucher = calculateVoucherAbsoluteValue(valorDoVoucher, BigDecimal.valueOf(order.getSubtotal() ));
- }
- LOG.info("Valor do voucher: " + valorDoVoucher);
- pagamento.setCodigoSite(siteId);
- pagamento.setCodigoPedido(order.getCode());
- pagamento.setMoeda(order.getCurrency().getIsocode());
- pagamento.setCapturado(APROVADO_CLEARSALE);
- // pagamento.setCodigoAntifraude(CLEARSALE);
- pagamento.setCodigoAntifraude("APPROVED");
- pagamento.setValor(valorDoVoucher);
- pagamento.setValorMoeda(valorDoVoucher);
- pagamento.setStatusVerificacaoFraude("APPROVED");
- pagamento.setCotacao(BigDecimal.valueOf(1));
- pagamento.setTipoPagamento(TipoDePagamento.VALE_CREDITO.getCode());
- pagamento.setParcelasCartao(1);
- pagamento.setCodigoAdministradora(0);
- pagamento.setVencimento(convertDate(order.getDate()));
- pagamento.setParcela(0);
- pagamento.setNumeroTitulo(voucherCode);
- //como o vale cr���������dito n���������o ��������� desconto ��������� realculado o valor de desconto
- BigDecimal outrosDescontos =
- BigDecimal.valueOf(order.getTotalDiscounts());
- outrosDescontos =
- outrosDescontos.subtract(
- BigDecimal.valueOf(
- Math.min(outrosDescontos.doubleValue(),
- valorDoVoucher.doubleValue())));
- LOG.info("Outros descontos: " + outrosDescontos);
- //totaldiscounts: 59,9 - voucher: 54,99 = 4,91 no caso do voucher, o totaldiscounts est������ englobando o valor do voucher. Se eu tirar o valor
- // do voucher, tenho o valor que efetivamente foi dado como desconto
- if( voucher.getFreeShipping() ){
- dadosPedido.getPedido().setValorFrete(BigDecimal.ZERO);
- outrosDescontos =
- outrosDescontos.subtract(
- BigDecimal.valueOf(
- Math.min(outrosDescontos.doubleValue(), order.getDeliveryCost())) );
- LOG.info("Voucher eh freeShipping. Outros descontos ajustados: " + outrosDescontos);
- }
- dadosPedido.getPedido().setDesconto( outrosDescontos );
- dadosPedido.getPagamento().add(pagamento);
- break;
- }
- }
- }
- private String getAddressType(final AddressModel add)
- {
- String home = "2";
- String company = "3";
- if (add.getTipoDeEndereco() == null)
- {
- return home;
- }
- if (add.getTipoDeEndereco().getCode().equals(
- TipoDeEndereco.RESIDENCIAL))
- {
- return home;
- }
- //TODO:
- //return "billing";
- return company;
- }
- private int getCodigoAdminstradoraCartao(final String brand)
- {
- if(brand == null)
- {
- return 0;
- }
- if (brand.equalsIgnoreCase("VISA"))
- {
- return 1;
- }
- if (brand.equalsIgnoreCase("MASTER"))
- {
- return 2;
- }
- if (brand.equalsIgnoreCase("DINERS"))
- {
- return 3;
- }
- if (brand.equalsIgnoreCase("AMEX"))
- {
- return 4;
- }
- if (brand.equalsIgnoreCase("HIPERCARD"))
- {
- return 5;
- }
- if (brand.equalsIgnoreCase("ELO"))
- {
- return 6;
- }
- if (brand.equalsIgnoreCase("HERING"))
- {
- return 7;
- }
- if (brand.equalsIgnoreCase("ELECTRON"))
- {
- return 8;
- }
- if (brand.equalsIgnoreCase("MAESTRO"))
- {
- return 9;
- }
- return 0;
- }
- private BigDecimal calculateDiscount(final List<DiscountValue> list) {
- BigDecimal total = new BigDecimal(0);
- for (final DiscountValue discount : list) {
- total = total.add(BigDecimal.valueOf(discount.getValue())) ;
- }
- return total;
- }
- private Resultado setUpResultado( final OrderModel orderModel, final Pedido pedido, final String siteId )
- {
- BankInformationsModel bankInformations =
- orderModel.getExchangeAndReturnProcess().getBankInformation();
- StringBuilder chave = new StringBuilder();
- chave.append("#" + bankInformations.getBank());
- chave.append("#" + bankInformations.getAccountHolder());
- chave.append("#" + bankInformations.getDocument());
- chave.append("#" + bankInformations.getAgency());
- chave.append("#" + bankInformations.getAccount());
- Resultado resultado = new Resultado();
- resultado.setTransacao("DEVOLUCAO_HYBRIS");
- resultado.setMensagem(chave.toString());
- resultado.setChave("CODIGO_SITE="+ siteId +"#PEDIDO=" + pedido.getCodigoPedido());
- return resultado;
- }
- /**
- * @return the omsOrderDao
- */
- public OMSOrderDao getOmsOrderDao() {
- return omsOrderDao;
- }
- /**
- * @param omsOrderDao the omsOrderDao to set
- */
- public void setOmsOrderDao(OMSOrderDao omsOrderDao) {
- this.omsOrderDao = omsOrderDao;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement