@Override
  public TaxStatus[] calculateTaxByShipping(TaxRequestInfo pTaxRequestInfo) {
    logDebug("CalculateTaxByShipping - Mystore");

    double orderAmount = 0.0D;
    double rates = 0.0D;
    double taxAmount = 0.0D;
    int i = 0;

    MyStoreTaxStatus[] retTaxStatus =
        new MyStoreTaxStatus[pTaxRequestInfo.getShippingDestinations().length];

    if (pTaxRequestInfo.getOrder() != null) {
      StoreOrderImpl order = (StoreOrderImpl) pTaxRequestInfo.getOrder();
      orderAmount = order.getPriceInfo().getAmount();
      /*taxOnItems = getTaxManager().getTaxForOrder(order);*/
    }

    for (ShippingDestination shippingDestination : pTaxRequestInfo.getShippingDestinations()) {

      if (isLoggingDebug()) {
        logDebug(
            "ACCL TAX PROCESSOR taxing a GROUP with amount : "
                + shippingDestination.getTaxableItemAmount()
                + shippingDestination.getShippingAddress().getPostalCode());
      }
      // TODO Change to repository lookup
      if (!StringUtils.isBlank(shippingDestination.getShippingAddress().getPostalCode())) {
        rates = getTaxRates().getTaxRate(shippingDestination.getShippingAddress().getPostalCode());
      }

      taxAmount = (orderAmount) * rates / 100;

      retTaxStatus[i] = new MyStoreTaxStatus();
      retTaxStatus[i].setAmount(getPricingTools().round(taxAmount));
      retTaxStatus[i].setTransactionSuccess(true);
      i++;
    }

    return retTaxStatus;
  }
Esempio n. 2
0
 public static String createQueryStringWithoutEmptyParams(
     DynamoHttpServletRequest pRequest, Set<ParameterName> params) {
   Iterator<ParameterName> it = params.iterator();
   StringBuilder sb = new StringBuilder();
   while (it.hasNext()) {
     ParameterName paramName = it.next();
     Object paramValue = pRequest.getLocalParameter(paramName);
     String sParamValue = paramValue != null ? paramValue.toString() : null;
     if (!StringUtils.isEmpty(sParamValue)) {
       sb.append(paramName.toString());
       sb.append('=');
       sb.append(sParamValue);
       sb.append('&');
     }
   }
   if (null != sb && sb.length() > 0) {
     sb.delete(sb.length() - 1, sb.length());
     sb.insert(0, '?');
   }
   return sb.toString();
 }
  /**
   * ToDo: DOCUMENT ME!
   *
   * @param pContext ToDo: DOCUMENT ME!
   * @throws ProcessException ToDo: DOCUMENT ME!
   */
  protected void doExecuteAction(ProcessExecutionContext pContext) throws ProcessException {
    if (mLogger.isLoggingDebug()) {
      mLogger.logDebug("Entering doExecuteAction");
      mLogger.logDebug("Message is " + pContext.getMessage());
    }

    InviteMessage inviteMessage = ((com.castorama.scenario.InviteMessage) pContext.getMessage());
    String email = inviteMessage.getReferee();

    if (StringUtils.isBlank(email)) {
      if (mLogger.isLoggingWarning()) {
        mLogger.logWarning("Empty email. Exiting.");
      }
      return;
    }

    if (mProfileTools.getItemFromEmail(email) != null) {
      if (mLogger.isLoggingWarning()) {
        mLogger.logWarning("User with email " + email + " already registered. Exiting.");
      }
      return;
    }

    RepositoryItem referrer = null;

    try {
      referrer = mProfileRepository.getItem(inviteMessage.getProfileId(), "user");
    } catch (RepositoryException e1) {
      throw new ProcessException("Can not find referrer with id=" + inviteMessage.getProfileId());
    }

    Set referees = (Set) referrer.getPropertyValue(PROPERTY_REFEREE);

    if (referees != null) {
      for (Iterator iterator = referees.iterator(); iterator.hasNext(); ) {
        RepositoryItem referee = (RepositoryItem) iterator.next();

        // check if the user is already invited
        if (((String) referee.getPropertyValue(PROPERTY_EMAIL)).equalsIgnoreCase(email)) {
          if (mLogger.isLoggingWarning()) {
            mLogger.logWarning(email + " is already invited by referrer. Exiting.");
          }
          return;
        }
      }
    }

    RepositoryItem refereePromo = mReferrerProgramConfig.getRefereePromotion();

    if (refereePromo == null) {
      throw new ProcessException("Referee promo is not set");
    }

    RepositoryItem referrerPromo = mReferrerProgramConfig.getReferrerPromotion();

    if (referrerPromo == null) {
      throw new ProcessException("Referrer promo is not set");
    }

    if (mLogger.isLoggingDebug()) {
      mLogger.logDebug("refereePromo is " + refereePromo);
      mLogger.logDebug("referrerPromo is " + referrerPromo);
    }

    String couponId = null;

    // find first available coupon
    try {
      Connection connection = null;
      ResultSet resultSet = null;
      PreparedStatement ps = null;

      try {
        connection = ((GSARepository) mProfileRepository).getDataSource().getConnection();

        ps = connection.prepareStatement(GET_COUPON_ID_FOR_REFEREE_SQL);
        ps.setString(1, refereePromo.getRepositoryId());
        resultSet = ps.executeQuery();

        if (resultSet.next()) {
          couponId = resultSet.getString("COUPON_ID");
        }
      } catch (Exception e) {
        throw new ProcessException("Can not retrieve coupon", e);
      } finally {
        if (resultSet != null) {
          try {
            resultSet.close();
          } catch (Exception e) {
          }
        }
        if (ps != null) {
          try {
            ps.close();
          } catch (Exception e) {
          }
        }
        if (connection != null) {
          try {
            connection.close();
          } catch (Exception e) {
          }
        }
      } // end try-catch-finally

      if (couponId == null) {
        throw new ProcessException("No coupons available");
      }

      if (mLogger.isLoggingDebug()) {
        mLogger.logDebug("Coupon found");
      }

      // creates referrer item
      MutableRepositoryItem referee =
          ((MutableRepository) mProfileRepository).createItem(ITEM_REFEREE);
      referee.setPropertyValue(PROPERTY_EMAIL, email);
      referee.setPropertyValue(PROPERTY_COUPONID, couponId);
      ((MutableRepository) mProfileRepository).addItem(referee);
      referees.add(referee);
      ((MutableRepository) mProfileRepository).updateItem((MutableRepositoryItem) referrer);

      if (mLogger.isLoggingDebug()) {
        mLogger.logDebug("Coupon assigned");
      }
    } catch (RepositoryException e) {
      throw new ProcessException("Can not send email", e);
    } // end try-catch

    String lastName = (String) referrer.getPropertyValue(LAST_NAME_PROFILE_PROP);
    String firstName = (String) referrer.getPropertyValue(FIRST_NAME_PROFILE_PROP);
    String referrerName = lastName + " " + firstName;

    try {
      Map<String, String> params = new HashMap<String, String>();
      params.put(EMAIL_PARAM_COUPON, couponId);
      params.put(EMAIL_PARAM_REFERRER, referrerName);

      Double adjuster = (Double) refereePromo.getPropertyValue(PROPERTY_ADJUSTER);
      params.put(EMAIL_PARAM_PROMO_AMOUNT, NUMBER_FORMAT.format(adjuster));
      String subject = String.format(Locale.FRANCE, mEmailSubject, referrerName);

      // send invitation to referee
      sendEmail(
          pContext,
          subject,
          mFromEmail,
          email,
          (String) getParameterValue(PARAM_TEMPLATE, pContext),
          params);

      params = new HashMap<String, String>();
      params.put(EMAIL_PARAM_REFERRER, referrerName);

      Date expDate = (Date) refereePromo.getPropertyValue(PROPERTY_END_USABLE);

      if (expDate != null) {
        params.put(EMAIL_PARAM_EXP_DATE, DATE_FORMAT.format(expDate));
      }

      adjuster = (Double) referrerPromo.getPropertyValue(PROPERTY_ADJUSTER);
      params.put(EMAIL_PARAM_PROMO_AMOUNT, NUMBER_FORMAT.format(adjuster));

      // send confirmation to referrer
      sendEmail(
          pContext,
          subject,
          mFromEmail,
          (String) referrer.getPropertyValue(PROPERTY_EMAIL),
          (String) getParameterValue(PARAM_REFERRER_TEMPLATE, pContext),
          params);
    } catch (ActionException e) {
      throw new ProcessException("Can not send email", e);
    } // end try-catch
  }
  /**
   * Forms correct trails for ajouters(pop-ups). Save ajouter's trail as map :ajouter id to trail.
   * If trail is empty or contains only one value(case for product listing (we don't show pivot
   * category facet at the UI)) so no one facet value was selected, so re-running search for pop-up
   * isn't necessary. the same situation for question parameter(search re-run isn't necessary).
   *
   * @param pRequest dynamo http request
   * @param pResponse dynamo http response
   * @throws ServletException
   * @throws IOException
   */
  public void service(DynamoHttpServletRequest pRequest, DynamoHttpServletResponse pResponse)
      throws ServletException, IOException {
    try {
      if (PerformanceMonitor.isEnabled()) {
        PerformanceMonitor.startOperation("search", "TEST:FacetedSearchPopUpFinder.service");
      }
      String initialTrail = pRequest.getParameter(TRAIL);

      if ((getCommerceFacetTrailTools() != null)
          && !StringUtils.isBlank(initialTrail)
          && (initialTrail.indexOf(":") != initialTrail.lastIndexOf(":"))) {
        List<FacetValue> trails =
            getCommerceFacetTrailTools().parseFacetValueString(initialTrail, null);

        Map<String, ArrayList<String>> facetIdToFacetValues =
            new HashMap<String, ArrayList<String>>();

        String firstSafeFacet;

        /*
         * pivot category || SRCH facet || root catgory facet - should stay the same; if this facet will be multiple
         * (facetId:facetValue1|facetValue2|...) So do check, the reason of this is .getTrailString() method returns
         * not correct value
         */
        if (trails.get(0) instanceof DisjunctionMultiValue) {
          firstSafeFacet = trails.get(0).toString();
          trails.remove(0);
        } else {
          firstSafeFacet = trails.get(0).getTrailString();
          trails.remove(0);
        }

        if (trails != null) {
          for (FacetValue fv : trails) {
            facetIdToFacetValues.put(fv.getFacet().getId(), new ArrayList());
          }

          for (FacetValue fv : trails) {
            if (facetIdToFacetValues.get(fv.getFacet().getId()) != null) {
              if (fv instanceof DisjunctionMultiValue) {
                ((ArrayList) facetIdToFacetValues.get(fv.getFacet().getId())).add(fv.toString());
              } else {
                ((ArrayList) facetIdToFacetValues.get(fv.getFacet().getId()))
                    .add(fv.getTrailString());
              }
            }
          }
          Map<String, String> resultedMapFacetIdToTrail = new HashMap<String, String>();

          // trails for queries
          for (Map.Entry<String, ArrayList<String>> excludedFacet :
              facetIdToFacetValues.entrySet()) {
            StringBuffer inludedFacetsSB = new StringBuffer();

            for (Map.Entry<String, ArrayList<String>> inludedFacets :
                facetIdToFacetValues.entrySet()) {
              if (!excludedFacet.getKey().equalsIgnoreCase(inludedFacets.getKey())) {
                for (String str : inludedFacets.getValue()) {
                  inludedFacetsSB.append(str).append(":");
                }
              }
            }

            // prepend first facet value (srch || pivot || root category)
            inludedFacetsSB.insert(0, ":").insert(0, firstSafeFacet);

            // delete extra last ":"
            if (inludedFacetsSB.lastIndexOf(":") == (inludedFacetsSB.length() - 1)) {
              inludedFacetsSB.replace(
                  inludedFacetsSB.lastIndexOf(":"), inludedFacetsSB.length(), "");
            }

            resultedMapFacetIdToTrail.put(excludedFacet.getKey(), inludedFacetsSB.toString());
          } // end for

          pRequest.setParameter(RESULTED_MAP_FACET_ID_TO_TRAIL, resultedMapFacetIdToTrail);
        } // end if
      } // end if
    } finally {
      if (PerformanceMonitor.isEnabled()) {
        PerformanceMonitor.endOperation("search", "TEST:FacetedSearchPopUpFinder.service");
      }
    } // end try-finally
    pRequest.serviceLocalParameter(OUTPUT, pRequest, pResponse);
  }
  /**
   * Méthode appelée par le webservice.
   *
   * @param a_requestXML la requête sous format XML envoyé par les clients
   * @param retourne un XML contenant la réponse
   */
  public String rechercheClients(String a_requestXML) {
    if (isLoggingDebug()) {
      logDebug(a_requestXML);
    }

    String l_resultXML = null;

    List<String> users = new ArrayList<String>();

    setTotalPagesCount(0);

    try {
      RechercheClientsRequest l_request =
          RechercheClientsRequest.unmarshal(new StringReader(a_requestXML));
      String l_id = l_request.getId();
      String l_email = l_request.getEmail();
      String l_prenom = l_request.getPrenom();
      String l_nom = l_request.getNom();
      String l_codePostal = l_request.getCodePostal();
      int l_pageSize = l_request.getPageSize();
      if (l_pageSize == 0) l_pageSize = getDefaultPageSize();
      int l_pageNumber = l_request.getPageNumber();
      if (l_pageNumber == 0) l_pageNumber = 1;
      int l_start = l_pageSize * (l_pageNumber - 1);
      int l_end = l_start + l_pageSize;

      if (!StringUtils.isBlank(l_id)) {

        if (isLoggingDebug()) {
          logDebug("Search by ID " + l_id + " ...");
        }

        // ------------------------------------------------------------
        // REG_CC_5_1
        // ------------------------------------------------------------

        if (!getWebServicesTools().isNumericOnly(l_id)) {
          l_resultXML = getXML(CODE_RETOUR_NUMERO_CLIENT_INCORRECT, null);
        } else {
          RepositoryItem item = getProfileRepository().getItem(l_id, "user");
          if (item != null) {
            users.add(item.getRepositoryId());
          }
        }

      } else if (!StringUtils.isBlank(l_email)) {

        if (isLoggingDebug()) {
          logDebug("Search by email " + l_email + " ...");
        }

        // ------------------------------------------------------------
        // REG_CC_5_2
        // ------------------------------------------------------------

        if (!getWebServicesTools().isEmail(l_email)) {
          l_resultXML = getXML(CODE_RETOUR_EMAIL_INCORRECT, null);
        } else {
          RepositoryItemDescriptor rid = getProfileRepository().getItemDescriptor("user");
          RepositoryView view = rid.getRepositoryView();
          RqlStatement req = RqlStatement.parseRqlStatement("login = ?0");
          RepositoryItem clients[] = req.executeQuery(view, new Object[] {l_email});

          if (clients != null && clients.length > l_start) {
            setTotalPagesCount((int) Math.ceil((double) clients.length / l_pageSize));
            l_end = Math.min(l_end, clients.length);
            for (int i = l_start; i < l_end; i++) {
              users.add(clients[i].getRepositoryId());
            }
          }
        }

      } else if (!StringUtils.isBlank(l_prenom) && !StringUtils.isBlank(l_nom)) {

        if (isLoggingDebug()) {
          logDebug("Search by firstName " + l_prenom + " and lastName " + l_nom + " ...");
        }

        // AP l_prenom = getWebServicesTools().removeAccentsAndCapitals(l_prenom);
        // AP l_nom = getWebServicesTools().removeAccentsAndCapitals(l_nom);

        // ------------------------------------------------------------
        // REG_CC_5_8
        // ------------------------------------------------------------

        // ------------------------------------------------------------
        // On récupére les profils correspondant au nom/prénom sans tenir
        // compte de la casse ni des accents
        // ------------------------------------------------------------

        StringBuilder query = new StringBuilder();
        query.append("lastName EQUALS IGNORECASE ?0 AND firstName EQUALS IGNORECASE ?1");
        if (!StringUtils.isBlank(l_codePostal)) {
          if (isLoggingDebug()) {
            logDebug("Search by postalCode " + l_codePostal + " ...");
          }

          query.append(" AND billingAddress.postalCode = ?2");
        }

        // ------------------------------------------------------------
        // REG_CC_5_7
        // ------------------------------------------------------------
        query.append(
            " ORDER BY firstName CASE IGNORECASE, lastName CASE IGNORECASE, billingAddress.postalCode, billingAddress.city CASE IGNORECASE");
        if (isLoggingDebug()) {
          logDebug("RQL:" + query);
        }

        // ------------------------------------------------------------
        // REG_CC_5_5
        // ------------------------------------------------------------
        RepositoryView view = getProfileRepository().getItemDescriptor("user").getRepositoryView();
        RqlStatement req = RqlStatement.parseRqlStatement(query.toString());
        RepositoryItem clients[] =
            req.executeQueryUncached(view, new Object[] {l_nom, l_prenom, l_codePostal});

        if (clients != null && clients.length > l_start) {
          setTotalPagesCount((int) Math.ceil((double) clients.length / l_pageSize));
          l_end = Math.min(l_end, clients.length);
          for (int i = l_start; i < l_end; i++) {
            users.add(clients[i].getRepositoryId());
          }
        }

        /*ap
        String[] ids = getWebServicesTools().getUserIdsMatchingFirstNameAndLastName(l_prenom, l_nom);

        if (ids != null && ids.length > 0)
        {
        	if (isLoggingDebug()) {
        		logDebug("Users matching firstName and lastName:" + Arrays.asList(ids));
        	}

        	// on construit la requête en commençant par rajouter ces IDs (qui matche firstName et lastName)
        	StringBuffer l_requete = new StringBuffer("ID IN { ");
        	for (int i = 0; i < ids.length; i++)
        	{
        		l_requete.append((i > 0 ? "," : "") + "\"" + ids[i] + "\"");
        	}
        	l_requete.append(" }");

        	// ------------------------------------------------------------
        	// REG_CC_5_4
        	// ------------------------------------------------------------
        	if (!StringUtils.isBlank(l_codePostal)) {
        		if (isLoggingDebug()) {
        			logDebug("Search by postalCode " + l_codePostal + " ...");
        		}

        		l_requete.append(" AND billingAddress.postalCode = ?0");
        	}

        	// ------------------------------------------------------------
        	// REG_CC_5_7
        	// ------------------------------------------------------------
        	l_requete.append(" ORDER BY firstName CASE IGNORECASE, lastName CASE IGNORECASE, billingAddress.postalCode, billingAddress.city CASE IGNORECASE");
        	if (isLoggingDebug()) {
        		logDebug("RQL:" +  l_requete);
        	}

        	// ------------------------------------------------------------
        	// REG_CC_5_5
        	// ------------------------------------------------------------
        	RepositoryView view = getProfileRepository().getItemDescriptor("user").getRepositoryView();
        	RqlStatement req = RqlStatement.parseRqlStatement(l_requete.toString());
        	RepositoryItem clients[] = req.executeQueryUncached(view, new Object[] { l_codePostal });

        	if (clients != null && clients.length > 0) {
        		for (int i = 0; i < clients.length; i++) {
        			users.add(clients[i].getPropertyValue("id"));
        		}
        	}

        }
        else
        {
        	if (isLoggingDebug()) {
        		logDebug("No users matching firstName and lastName");
        	}
        }

        */

      } else if (!StringUtils.isBlank(l_nom)) {
        if (isLoggingDebug()) {
          logDebug("Search by lastName " + l_nom + " ...");
        }

        StringBuilder query = new StringBuilder();
        query.append("lastName EQUALS IGNORECASE ?0");
        if (!StringUtils.isBlank(l_codePostal)) {
          if (isLoggingDebug()) {
            logDebug("Search by postalCode " + l_codePostal + " ...");
          }

          query.append(" AND billingAddress.postalCode = ?1");
        }

        query.append(
            " ORDER BY firstName CASE IGNORECASE, lastName CASE IGNORECASE, billingAddress.postalCode, billingAddress.city CASE IGNORECASE");
        if (isLoggingDebug()) {
          logDebug("RQL:" + query);
        }

        RepositoryView view = getProfileRepository().getItemDescriptor("user").getRepositoryView();
        RqlStatement req = RqlStatement.parseRqlStatement(query.toString());
        RepositoryItem clients[] =
            req.executeQueryUncached(view, new Object[] {l_nom, l_codePostal});

        if (clients != null && clients.length > l_start) {
          setTotalPagesCount((int) Math.ceil((double) clients.length / l_pageSize));
          l_end = Math.min(l_end, clients.length);
          for (int i = l_start; i < l_end; i++) {
            users.add(clients[i].getRepositoryId());
          }
        }

      } else if (!StringUtils.isBlank(l_prenom) && !StringUtils.isBlank(l_codePostal)) {
        if (isLoggingDebug()) {
          logDebug("Search by firstName " + l_prenom + " and postalCode " + l_codePostal + " ...");
        }

        StringBuilder query = new StringBuilder();
        query.append("firstName EQUALS IGNORECASE ?0 AND billingAddress.postalCode = ?1");

        query.append(
            " ORDER BY firstName CASE IGNORECASE, lastName CASE IGNORECASE, billingAddress.postalCode, billingAddress.city CASE IGNORECASE");
        if (isLoggingDebug()) {
          logDebug("RQL:" + query);
        }

        RepositoryView view = getProfileRepository().getItemDescriptor("user").getRepositoryView();
        RqlStatement req = RqlStatement.parseRqlStatement(query.toString());
        RepositoryItem clients[] =
            req.executeQueryUncached(view, new Object[] {l_prenom, l_codePostal});

        if (clients != null && clients.length > l_start) {
          setTotalPagesCount((int) Math.ceil((double) clients.length / l_pageSize));
          l_end = Math.min(l_end, clients.length);
          for (int i = l_start; i < l_end; i++) {
            users.add(clients[i].getRepositoryId());
          }
        }

      } else if (!StringUtils.isBlank(l_codePostal)) {
        if (isLoggingDebug()) {
          logDebug("Search by postalCode " + l_codePostal + " ...");
        }

        StringBuilder query = new StringBuilder();
        query.append("billingAddress.postalCode = ?0");

        query.append(
            " ORDER BY firstName CASE IGNORECASE, lastName CASE IGNORECASE, billingAddress.postalCode, billingAddress.city CASE IGNORECASE");
        if (isLoggingDebug()) {
          logDebug("RQL:" + query);
        }

        RepositoryView view = getProfileRepository().getItemDescriptor("user").getRepositoryView();
        RqlStatement req = RqlStatement.parseRqlStatement(query.toString());
        RepositoryItem clients[] = req.executeQueryUncached(view, new Object[] {l_codePostal});

        if (clients != null && clients.length > l_start) {
          setTotalPagesCount((int) Math.ceil((double) clients.length / l_pageSize));
          l_end = Math.min(l_end, clients.length);
          for (int i = l_start; i < l_end; i++) {
            users.add(clients[i].getRepositoryId());
          }
        }

      } else {

        // ------------------------------------------------------------
        // REG_CC_5_3
        // ------------------------------------------------------------

        l_resultXML = getXML(CODE_RETOUR_NOM_ET_PRENOM_VIDE, null);
      }

      // ------------------------------------------------------------
      // REG_CC_5_9
      // ------------------------------------------------------------

      // si aucune erreur, alors tout s'est bien passé (!). On set le code d'erreur (clients trouvés
      // ou non)
      if (l_resultXML == null) {
        /*for (Iterator l_it = users.iterator(); l_it.hasNext();)
        {
        	// on vérifie que les ids existent
        	String l_idToCheck = (String) l_it.next();
        	if (getProfileRepository().getItem(l_idToCheck, "user") == null)
        	{
        		if (isLoggingDebug()) {
        			logDebug("ID " + l_idToCheck + " doesn't exist, removing ...");
        		}
        		l_it.remove();
        	}
        }
        */

        if (isLoggingDebug()) {
          logDebug("Users list:" + users);
        }

        if (users.size() > 0) {
          l_resultXML = getXML(CODE_RETOUR_OK, users);
        } else {
          l_resultXML = getXML(CODE_RETOUR_AUCUN_RESULTAT, null);
        }
      }

    } catch (MarshalException l_me) {
      if (isLoggingError()) {
        logError(l_me);
      }
    } catch (ValidationException l_ve) {
      if (isLoggingError()) {
        logError(l_ve);
      }
    } catch (RepositoryException l_re) {
      if (isLoggingError()) {
        logError(l_re);
      }
    } catch (Exception l_e) {
      if (isLoggingError()) {
        logError(l_e);
      }
    }

    if (l_resultXML == null) {
      if (isLoggingDebug()) {
        logDebug("Internal error. See ATG logs for more information.");
      }
      l_resultXML = getXML(CODE_RETOUR_INCONNU, users);
    }

    if (isLoggingDebug()) {
      logDebug(l_resultXML);
    }
    return l_resultXML;
  }