Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package webservices.shipping;
- import java.io.IOException;
- public class TrackingStatusService extends RibeiroDroplet {
- private static final String PARENT_NODE = "Estado_Entregas";
- private static final String PARENT_NODE_SP ="Estado_Stored_PickUp";
- private static final String DELIVERY_STATUS = "Status_Entrega";
- private static final String DELIVERY_STATUS_SP = "Status";
- private static final int STORE_PICKUP = 2;
- private static final int CR_OCA = 3;
- private static final String CERRADO = "C";
- private static final String COL_DESPACHO ="DphEnt";
- protected static ApplicationLogging mLogging = ClassLoggingFactory.getFactory().getLoggerForClass(TrackingStatusService.class);
- private String puntoVenta;
- private String nFactura;
- private String lFactura;
- private int tipoEnvio;
- private String orderId;
- //CONFIG
- private int diasAEvaluar;
- private String cantidadAdicional;
- private String username;
- private String password;
- private String soapEndpointUrl;
- private String soapAction;
- private String msgAnnulled;
- private String msgPreparation;
- private String msgConfirmed;
- private String msgDelivered;
- private String msgInRoute;
- private String msgInSucursal;
- private String msgNotFoundSap;
- private String msgRetired;
- // INPUT PARAMETERS
- private static final String NFACTURA = "numFactura";
- private static final String LFACTURA = "letraFactura";
- private static final String PUNTOVENTA = "puntoVenta";
- private static final String TIPOENVIO = "tipoEnvio";
- private static final String ORDERID = "orderId";
- // OUTPUT PARAMETERS
- private static final String MENSAJE = "mensaje";
- private static final String NROGUIA = "nroGuia";
- private static final String FECHA_ENTREGA = "fechaEntrega";
- private static final String FRANJA_HORARIA = "franjaHoraria";
- //Responses
- private static final String ANULADA= "Entrega ANULADA";
- private static final String ENTREGA="Con Entrega";
- private static final String ENTREGA_TRANSPORTE="Con Entrega - Con Transporte";
- private static final String ENTREGA_TRANSPORTE_INI="Con Entrega - Con Transporte Iniciado";
- private static final String ENTREGA_TRANSPORTE_FIN="Con Entrega - Con Transporte Finalizado";
- private static final String CON_FRANJA = "Con Entrega - Con Transporte Finalizado - Fecha:"; //dd/MM/yyyy Franja Horaria: 8 a 14."
- private static final String ENTREGA_DEV="Con Entrega - Devuelta";
- private static final String ENTREGA_PDEV="Con Entrega - Para Devolver";
- private static final String ENTREGA_PENDIENTE="Con Entrega - Pendiente de procesar";
- private static final String SIN_ENTREGA="Sin Entrega";
- private static final String SIN_ENTREGA_CANC="Sin Entrega - Cancelada";
- private static final String SIN_ENTREGA_PCANC="Sin Entrega - Para Cancelar";
- private static final String SIN_ENTREGA_PENDIENTE="Sin Entrega - Pendiente de procesar";
- private static final String REGISTRO_DUPLICADO="Registro Duplicado";
- //Store Pickup Responses
- private static final String ENTREGADO = "Entregado al Cliente";
- private static final String PENDIENTE = "Pendiente de Procesar";
- private static final String TRASLADO_SUCURSAL = "Pedido de traslado a sucursal";
- private static final String ENTREGADO_PARCIAL = "Entregado Parcialmente al Cliente";
- private static final String EN_SUCURSAL = "En sucursal";
- private static final String NO_DATA_SAP = "No existe registro en la tabla ZPI_TRASLADOSen SAP para ese Punto de venta, Factura y Letra.";
- /* (non-Javadoc)
- * @see atg.servlet.DynamoServlet#service(atg.servlet.DynamoHttpServletRequest, atg.servlet.DynamoHttpServletResponse)
- */
- @Override
- public void service(DynamoHttpServletRequest request,
- DynamoHttpServletResponse response) throws ServletException, IOException {
- setPuntoVenta(request.getParameter(PUNTOVENTA));
- setnFactura(request.getParameter(NFACTURA));
- setlFactura(request.getParameter(LFACTURA));
- setTipoEnvio(Integer.parseInt(request.getParameter(TIPOENVIO)));
- setOrderId(request.getParameter(ORDERID));
- String mensaje = "";
- //Se evalua el tipo de envío
- if(getTipoEnvio()== CR_OCA){
- String orderId = request.getParameter(ORDERID);
- mensaje=getMsgPreparation();
- String nroGuia = findNroGuia(orderId);
- if (nroGuia!=null && !nroGuia.isEmpty()) {
- mensaje = getMsgInSucursal();
- request.setParameter(NROGUIA, nroGuia);
- }
- }else{
- //Se invoca el webService y se extrae el estado.
- mensaje = getStatus(getSoapEndpointUrl(), getSoapAction());
- }
- //Se maneja el mensaje, y se obtiene fecha de entrega y franja horaria cuando corresponde.
- String[] results = handleResponse(mensaje);
- //Se setean los parametros de salida.
- request.setParameter(MENSAJE, results[0]);
- request.setParameter(FECHA_ENTREGA, results[1]);
- request.setParameter(FRANJA_HORARIA, results[2]);
- request.serviceLocalParameter(OUTPUT, request, response);
- }
- /*
- * Consulta a la tabla DPDPCHO de Gex Central si la orden si el despacho se encuentra cerrado (Dphent == 'C').
- * Para casos de Store Pickup, la tabla DPDPCHO se actualiza correctamente al día siguiente de la entrega al cliente. Para Entrega Domiciliaria, DPDPCHO se
- * actualiza de la misma manera cuando el despacho es hecho por una sucursal, pero cuando el estado de la orden en DPDPCHO nunca pasa a 'C'.
- */
- private boolean checkDeliveryOnDB(){
- Statement stmt = null;
- String query = null;
- Connection connection = null;
- try {
- connection = DataBaseUtils.connectToExternal(DataBaseUtils.Bases.CENTRAL);
- //Consulta a GEXCENTRAL para obtener el estado de despacho ("C"=Cerrado, "P"=Pendiente)
- query = "select "+COL_DESPACHO+"from dbo.DPDPCHO where DphPVt="+getPuntoVenta()+" and DphNum="+getnFactura()+" and DphLtf='"+getlFactura()+"' and tcocod='DEN'";
- stmt = connection.createStatement();
- ResultSet results = stmt.executeQuery(query);
- String estado = "";
- boolean isDelivered=true;
- if (results.isBeforeFirst()) {
- while (results.next()) {
- estado = results.getString(COL_DESPACHO);
- if (!estado.equalsIgnoreCase(CERRADO)) {
- isDelivered=false;
- break;
- }
- }
- }
- return isDelivered;
- } catch (Exception ex) {
- logError(ex);
- } finally{
- if(connection != null){
- try {
- connection.close();
- } catch (SQLException e) {
- logError(e);
- }
- }
- }
- return false;
- }
- /*
- * Metodo que recupera el número de guía de la orden con tipo de envío Centro de retiro OCA
- */
- private String findNroGuia(String orderId){
- OrderManager orderManager = (OrderManager) Nucleus.getGlobalNucleus()
- .resolveName("/atg/commerce/order/OrderManager");
- try {
- RibeiroOrder order = (RibeiroOrder) orderManager.loadOrder(orderId);
- String nroGuia = order.getNroGuia();
- return nroGuia;
- } catch (Exception e) {
- if (mLogging.isLoggingError()) {
- mLogging.logError(e);
- }
- }
- return null;
- }
- /*
- * Metodo que invoca el WS de stock mediante RibeiroStockTools, envíando la orden, el número de sucursal extraído del Shipping Group y la cantidad de unidades adicionales a sumar a la verificación de stock.
- * La cantidad adicional se envía concatenada al string "cantidad=", que luego se recupera en RibeiroStockTools.consultaGEXSinHacerReserva() y RibeiroStockTools.consultaSAPSinHacerReserva().
- */
- private boolean checkStockAvailability(String orderId){
- StockWebServicesParameters swsp = (StockWebServicesParameters) Nucleus.getGlobalNucleus()
- .resolveName("/atg/commerce/catalog/stock/StockWebServicesParameters");
- boolean resGex = false;
- boolean resSap = false;
- String[] codSucursales = new String[1];
- String storePickupId = "";
- //Se setea la cantidad a sumarle a la validación de stock en un String.
- String cantAdicional= "cantidad="+getCantidadAdicional();
- OrderManager orderManager = (OrderManager) Nucleus.getGlobalNucleus()
- .resolveName("/atg/commerce/order/OrderManager");
- RibeiroOrder order;
- try {
- order = (RibeiroOrder) orderManager.loadOrder(orderId);
- List<ShippingGroup> shippings = order.getShippingGroups();
- //Recorre los Shipping Groups para obtener el número de sucursal
- for (ShippingGroup sg : shippings) {
- if(!(sg instanceof HardgoodShippingGroup)) {
- continue;
- }
- String shippingMethod = ((RibeiroHardgoodShippingGroup) sg).getShippingMethod();
- if (shippingMethod.equalsIgnoreCase("store pickup")) {
- storePickupId = ((RibeiroHardgoodShippingGroup) sg).getStorePickupId();
- if (storePickupId != null && !storePickupId.trim().isEmpty()) {
- try {
- codSucursales[0] = storePickupId;
- RepositoryItem store = RepositoryUtils.findOne("/atg/commerce/locations/LocationRepository", "store", RqlStatement.parseRqlStatement("locationId = ?0"), new Object[]{storePickupId}, null);
- /* Obtengo el numero de sucursal en base al locationId */
- codSucursales[0] = (String)store.getPropertyValue("name");
- } catch (NumberFormatException ex) {
- } catch (RepositoryException e) {
- if (mLogging.isLoggingError()) {
- mLogging.logError(e);
- }
- }
- }
- }
- if(swsp.isEnabledGex()) {
- try {
- //Invoco la consulta de stock
- resGex = RibeiroStockTools.consultaGEXSinHacerReserva(order,codSucursales, cantAdicional);
- } catch (Exception ex) {
- if (mLogging.isLoggingError()) {
- mLogging.logError(ex);
- }
- resGex = false;
- }
- }
- if(swsp.isEnabledSap() && resGex == false ) {
- //Invoco la consulta de stock
- resSap = RibeiroStockTools.consultaSAPSinHacerReserva(order,codSucursales,cantAdicional);
- }
- }
- } catch (CommerceException e) {
- mLogging.logError(e);
- }
- return (resGex || resSap);
- }
- /*
- * Retorna un array. En su primera posición se encuentra el mensaje, en la segunda la fecha de entrega
- * y por ultimo en la tercera posición, la franja horaria.
- */
- private String[] handleResponse(String msg){
- String[] results = new String[3];
- //Se chequea si el mensaje contiene la fecha y franja horaria.
- if(msg.indexOf(CON_FRANJA)!=-1){
- String franja = "";
- String fecha = "";
- msg = msg.split("-")[2];
- results[0] = getMsgDelivered();
- fecha = msg.split(":")[1];
- fecha = fecha.replace("Franja Horaria","");
- franja = msg.split(":")[2];
- //Se verifica si los días transcurridos son mayores a la cantidad de días necesarios para dar
- //el pedido por entregado
- if(checkDeliveryByDate(fecha)){
- return results;
- }else if(checkDeliveryOnDB()){ //Se verifica el estado del DESPACHO en BD, si está cerrado el pedido ya fue entregado.
- return results;
- }else{//Se devuelven los datos para ser mostrados.
- results[0] = getMsgInRoute();
- results[1] = fecha;
- results[2] = franja;
- return results;
- }
- }
- switch (msg) {
- case ENTREGA: case ENTREGA_TRANSPORTE: case ENTREGA_TRANSPORTE_INI: case ENTREGA_PENDIENTE:
- case REGISTRO_DUPLICADO:
- results[0] = getMsgPreparation();
- break;
- case ANULADA: case ENTREGA_DEV: case ENTREGA_PDEV:
- case SIN_ENTREGA_CANC: case SIN_ENTREGA_PCANC:
- results[0] = getMsgAnnulled();
- break;
- case SIN_ENTREGA: case SIN_ENTREGA_PENDIENTE: case PENDIENTE:
- results[0] = getMsgConfirmed();
- break;
- case ENTREGA_TRANSPORTE_FIN:
- results[0] = getMsgInRoute();
- break;
- case ENTREGADO:
- results[0] = getMsgRetired();
- case TRASLADO_SUCURSAL: case ENTREGADO_PARCIAL: case EN_SUCURSAL:
- //Se chequea si hay stock disponible en la sucursal.
- if (checkStockAvailability(getOrderId())) {
- msg = getMsgInSucursal();
- }else{
- msg = getMsgPreparation();
- }
- case NO_DATA_SAP:
- results[0] = getMsgNotFoundSap();
- break;
- default:
- results[0] = msg;
- break;
- }
- return results;
- }
- /*
- * Metodo que verifica la cantidad de días transcurridos desde la fecha de entrega y la compara con la variable díasAEvaluar, que contiene la cantidad de días que deben transcurrir para dar una orden por entregada.
- */
- private boolean checkDeliveryByDate(String fecha){
- Date today = new Date();
- SimpleDateFormat parser = new SimpleDateFormat("dd/MM/yyyy");
- Date fechaEntrega;
- try {
- fechaEntrega = parser.parse(fecha);
- } catch (ParseException e) {
- logError(e);
- fechaEntrega=today;
- }
- long diffInMillies = today.getTime() - fechaEntrega.getTime();
- long diasTranscurridos = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
- return (diasTranscurridos >= getDiasAEvaluar());
- }
- /*
- * Metodo que crea el SoapEnvelope con los parametros de la orden: Punto de venta, número y letra de la factura.
- */
- private void createSoapEnvelope(SOAPMessage soapMessage, String nFactura, String lFactura, String puntoVenta) throws SOAPException {
- SOAPPart soapPart = soapMessage.getSOAPPart();
- String myNamespace = "con";
- String myNamespaceURI = "http://ribeiro.com.ar/pi/consultaestado";
- // SOAP Envelope
- SOAPEnvelope envelope = soapPart.getEnvelope();
- envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);
- // SOAP Body
- SOAPBody soapBody = envelope.getBody();
- SOAPElement soapBodyElem = soapBody.addChildElement("MT_Estado_Request", myNamespace);
- //Se crean los elementos
- SOAPElement numFacturaNode = soapBodyElem.addChildElement("NumFactura");
- SOAPElement letraFacturaNode = soapBodyElem.addChildElement("LetraFactura");
- SOAPElement puntaVentaNode = soapBodyElem.addChildElement("PuntoVenta");
- //PARAMS
- numFacturaNode.addTextNode(nFactura);
- letraFacturaNode.addTextNode(lFactura);
- puntaVentaNode.addTextNode(puntoVenta);
- }
- /*
- * Metodo que invoca el WS Soap y extrae el estado de la respuesta.
- */
- private String getStatus(String soapEndpointUrl, String soapAction) {
- String estado = "";
- try {
- // Crea SOAP Connection
- SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
- SOAPConnection soapConnection = soapConnectionFactory.createConnection();
- // Envía SOAP Message al SOAP Server
- SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);
- SOAPBody soapResponseBody = soapResponse.getSOAPBody();
- String parent = "";
- String statusNode = "";
- if (getTipoEnvio()==STORE_PICKUP) {
- parent=PARENT_NODE_SP;
- statusNode=DELIVERY_STATUS_SP;
- }else{
- parent=PARENT_NODE;
- statusNode=DELIVERY_STATUS;
- }
- //Extrae los items de la respuesta.
- NodeList subList = soapResponseBody.getElementsByTagName(parent);
- NodeList innerResultList = null;
- //Recorre los items y extrae el estado de cada uno.
- for (int i = 0; i < subList.getLength(); i++) {
- innerResultList = subList.item(i).getChildNodes();
- for (int j = 0; j < innerResultList.getLength(); j++) {
- if (innerResultList.item(j).getNodeName().equalsIgnoreCase(statusNode)) {
- estado = innerResultList.item(j).getTextContent();
- break;
- }
- }
- if (!estado.equalsIgnoreCase(ENTREGA_TRANSPORTE_FIN) || !estado.equalsIgnoreCase(ENTREGA_TRANSPORTE)
- || estado.indexOf(CON_FRANJA)!=-1 || estado.equalsIgnoreCase(PENDIENTE)) {
- break;
- }
- }
- soapConnection.close();
- return estado;
- } catch (Exception e) {
- mLogging.logError(e);
- }
- return estado;
- }
- /*
- * Metodo que crea el mensaje SOAP y le agrega las credenciales y la SOAPAction al header.
- */
- private SOAPMessage createSOAPRequest(String soapAction) throws Exception {
- MessageFactory messageFactory = MessageFactory.newInstance();
- SOAPMessage soapMessage = messageFactory.createMessage();
- createSoapEnvelope(soapMessage, getnFactura(), getlFactura(), getPuntoVenta());
- //Encodea las credenciales
- String authorization = Base64.encode((getUsername()+":"+getPassword()).getBytes());
- //Setea las credenciales y el soapAction al header.
- MimeHeaders headers = soapMessage.getMimeHeaders();
- headers.addHeader("SOAPAction", soapAction);
- headers.addHeader("Authorization", "Basic " + authorization);
- soapMessage.saveChanges();
- return soapMessage;
- }
- /**
- * @return the soapEndpointUrl
- */
- public String getSoapEndpointUrl() {
- return soapEndpointUrl;
- }
- /**
- * @param soapEndpointUrl the soapEndpointUrl to set
- */
- public void setSoapEndpointUrl(String soapEndpointUrl) {
- this.soapEndpointUrl = soapEndpointUrl;
- }
- /**
- * @return the soapAction
- */
- public String getSoapAction() {
- return soapAction;
- }
- /**
- * @param soapAction the soapAction to set
- */
- public void setSoapAction(String soapAction) {
- this.soapAction = soapAction;
- }
- /**
- * @return the msgAnnulled
- */
- public String getMsgAnnulled() {
- return msgAnnulled;
- }
- /**
- * @param msgAnnulled the msgAnnulled to set
- */
- public void setMsgAnnulled(String msgAnnulled) {
- this.msgAnnulled = msgAnnulled;
- }
- /**
- * @return the msgPreparation
- */
- public String getMsgPreparation() {
- return msgPreparation;
- }
- /**
- * @param msgPreparation the msgPreparation to set
- */
- public void setMsgPreparation(String msgPreparation) {
- this.msgPreparation = msgPreparation;
- }
- /**
- * @return the msgDelivered
- */
- public String getMsgDelivered() {
- return msgDelivered;
- }
- /**
- * @param msgDelivered the msgDelivered to set
- */
- public void setMsgDelivered(String msgDelivered) {
- this.msgDelivered = msgDelivered;
- }
- /**
- * @return the username
- */
- public String getUsername() {
- return username;
- }
- /**
- * @param username the username to set
- */
- public void setUsername(String username) {
- this.username = username;
- }
- /**
- * @return the password
- */
- public String getPassword() {
- return password;
- }
- /**
- * @param password the password to set
- */
- public void setPassword(String password) {
- this.password = password;
- }
- /**
- * @return the msgNotFoundSap
- */
- public String getMsgNotFoundSap() {
- return msgNotFoundSap;
- }
- /**
- * @param msgNotFoundSap the msgNotFoundSap to set
- */
- public void setMsgNotFoundSap(String msgNotFoundSap) {
- this.msgNotFoundSap = msgNotFoundSap;
- }
- /**
- * @return the msgInRoute
- */
- public String getMsgInRoute() {
- return msgInRoute;
- }
- /**
- * @param msgInRoute the msgInRoute to set
- */
- public void setMsgInRoute(String msgInRoute) {
- this.msgInRoute = msgInRoute;
- }
- /**
- * @return the msgInSucursal
- */
- public String getMsgInSucursal() {
- return msgInSucursal;
- }
- /**
- * @param msgInSucursal the msgInSucursal to set
- */
- public void setMsgInSucursal(String msgInSucursal) {
- this.msgInSucursal = msgInSucursal;
- }
- /**
- * @return the cantidadAdicional
- */
- public String getCantidadAdicional() {
- return cantidadAdicional;
- }
- /**
- * @param cantidadAdicional the cantidadAdicional to set
- */
- public void setCantidadAdicional(String cantidadAdicional) {
- this.cantidadAdicional = cantidadAdicional;
- }
- /**
- * @return the msgConfirmed
- */
- public String getMsgConfirmed() {
- return msgConfirmed;
- }
- /**
- * @param msgConfirmed the msgConfirmed to set
- */
- public void setMsgConfirmed(String msgConfirmed) {
- this.msgConfirmed = msgConfirmed;
- }
- /**
- * @return the diasAEvaluar
- */
- public int getDiasAEvaluar() {
- return diasAEvaluar;
- }
- /**
- * @param diasAEvaluar the diasAEvaluar to set
- */
- public void setDiasAEvaluar(int diasAEvaluar) {
- this.diasAEvaluar = diasAEvaluar;
- }
- /**
- * @return the puntoVenta
- */
- public String getPuntoVenta() {
- return puntoVenta;
- }
- /**
- * @param puntoVenta the puntoVenta to set
- */
- public void setPuntoVenta(String puntoVenta) {
- this.puntoVenta = puntoVenta;
- }
- /**
- * @return the nFactura
- */
- public String getnFactura() {
- return nFactura;
- }
- /**
- * @param nFactura the nFactura to set
- */
- public void setnFactura(String nFactura) {
- this.nFactura = nFactura;
- }
- /**
- * @return the lFactura
- */
- public String getlFactura() {
- return lFactura;
- }
- /**
- * @param lFactura the lFactura to set
- */
- public void setlFactura(String lFactura) {
- this.lFactura = lFactura;
- }
- /**
- * @return the tipoEnvio
- */
- public int getTipoEnvio() {
- return tipoEnvio;
- }
- /**
- * @param tipoEnvio the tipoEnvio to set
- */
- public void setTipoEnvio(int tipoEnvio) {
- this.tipoEnvio = tipoEnvio;
- }
- /**
- * @return the msgRetired
- */
- public String getMsgRetired() {
- return msgRetired;
- }
- /**
- * @param msgRetired the msgRetired to set
- */
- public void setMsgRetired(String msgRetired) {
- this.msgRetired = msgRetired;
- }
- /**
- * @return the orderId
- */
- public String getOrderId() {
- return orderId;
- }
- /**
- * @param orderId the orderId to set
- */
- public void setOrderId(String orderId) {
- this.orderId = orderId;
- }
- }
Add Comment
Please, Sign In to add comment