@Override
  public void prepareModule() throws Exception {
    Context ctx =
        (Context) super.getServletRequest().getSession().getAttribute(ProfileConstants.context);
    Integer merchantid = ctx.getMerchantid();

    ReferenceService rservice =
        (ReferenceService) ServiceFactory.getService(ServiceFactory.ReferenceService);

    Locale locale = getLocale();

    String country = locale.getCountry();
    if (locale.getVariant().equals("EUR")) {
      country = "X1";
    }

    Map packages = ShippingUtil.buildPackageMap(moduleid, locale);
    if (packages != null) {
      setPackageMap(packages);
    }

    // get merchant configs
    MerchantService mservice =
        (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);

    ConfigurationResponse config = mservice.getConfigurationByModule(moduleid, merchantid);
    this.setConfigurations(config);
  }
  @Override
  public void prepareModule() throws Exception {

    Context ctx =
        (Context) super.getServletRequest().getSession().getAttribute(ProfileConstants.context);
    Integer merchantid = ctx.getMerchantid();

    MerchantService mservice =
        (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);

    String text =
        LabelUtil.getInstance().getText(super.getLocale(), "label.payment.methods.title.papal");
    this.setMessage(text);

    MerchantStore mstore = mservice.getMerchantStore(merchantid);

    if (mstore == null) {
      MessageUtil.addErrorMessage(
          super.getServletRequest(),
          LabelUtil.getInstance().getText("errors.profile.storenotcreated"));
    }

    ConfigurationResponse config = mservice.getConfigurationByModule(moduleid, merchantid);
    this.setConfigurations(config);
  }
  /** Get customer for a customerId and merchantId */
  @WebMethod
  public @WebResult GetCustomerWebServiceResponse getCustomer(
      @WebParam(name = "credentials") WebServiceCredentials credentials,
      @WebParam(name = "customer") Customer customer) {
    MessageSource messageSource = (MessageSource) SpringUtil.getBean("messageSource");

    Locale locale = LocaleUtil.getDefaultLocale();
    if (StringUtils.isNotBlank(customer.getCustomerLang())) {
      locale = LocaleUtil.getLocale(customer.getCustomerLang());
    }

    GetCustomerWebServiceResponse response = new GetCustomerWebServiceResponse();
    try {

      if (customer.getCustomerId() == 0) {
        setStatusMsg(messageSource, locale, response, "messages.authorization", 0);
        return response;
      }
      // check credentials
      validateCredentials(locale, credentials);

      CustomerService cservice =
          (CustomerService) ServiceFactory.getService(ServiceFactory.CustomerService);
      com.salesmanager.core.entity.customer.Customer entityCustomer =
          cservice.getCustomer(customer.getCustomerId());
      if (entityCustomer == null) {
        setStatusMsg(messageSource, locale, response, "messages.customer.doesnotexist", 0);
        return response;
      }

      if (entityCustomer.getMerchantId() != credentials.getMerchantId()) {
        setStatusMsg(messageSource, locale, response, "messages.authorization", 0);
        return response;
      }

      Customer webCustomer = new Customer();
      BeanUtils.copyProperties(webCustomer, entityCustomer);
      response.setCustomer(webCustomer);
      response.setStatus(1);

    } catch (Exception e) {

      if (e instanceof ServiceException) {
        String[] msg = {((ServiceException) e).getMessage()};
        response.setMessages(msg);
        response.setStatus(0);
      } else {

        log.error("Exception occurred while creating Customer", e);
        response.setMessages(
            new String[] {messageSource.getMessage("errors.technical", null, locale)});
        response.setStatus(0);
      }
    }
    return response;
  }
  @Override
  public void deleteModule() throws Exception {
    Context ctx =
        (Context) super.getServletRequest().getSession().getAttribute(ProfileConstants.context);
    Integer merchantid = ctx.getMerchantid();

    MerchantService mservice =
        (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
    mservice.cleanConfigurationLikeKeyModule("SHP_RT_", moduleid, merchantid);
  }
  @Override
  public void saveModule() throws Exception {

    Context ctx =
        (Context) super.getServletRequest().getSession().getAttribute(ProfileConstants.context);
    Integer merchantid = ctx.getMerchantid();

    // need validation
    boolean hasError = false;

    if (StringUtils.isBlank(this.getKeys().getProperties1())) {
      addFieldError("keys.properties1", getText("error.payment.paypal.userid.required"));
      hasError = true;
    }

    if (StringUtils.isBlank(this.getKeys().getProperties2())) {
      addFieldError("keys.properties2", getText("error.payment.paypal.password.required"));
      hasError = true;
    }

    if (StringUtils.isBlank(this.getKeys().getProperties3())) {
      addFieldError("keys.properties3", getText("error.payment.paypal.signature.required"));
      hasError = true;
    }

    String value2 = this.getKeys().getProperties5();
    this.getKeys().setProperties5("");

    String value1 = MerchantConfigurationUtil.getConfigurationValue(this.getKeys(), "|");

    ConfigurationResponse vo = this.getConfigurations();
    MerchantConfiguration conf = null;
    if (vo != null) {
      conf = (MerchantConfiguration) vo.getConfiguration(PaymentConstants.PAYMENT_PAYPALNAME);
    }
    if (conf != null) {
      conf.setConfigurationValue(value1);
      conf.setConfigurationValue1(value2);

    } else {

      conf = new MerchantConfiguration();
      conf.setMerchantId(merchantid);

      conf.setConfigurationModule(moduleid);
      conf.setConfigurationKey(
          PaymentConstants.MODULE_PAYMENT + PaymentConstants.PAYMENT_PAYPALNAME);
      conf.setConfigurationValue(value1); // userid | password | signature
      conf.setConfigurationValue1(value2); // environment
    }

    MerchantService mservice =
        (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
    mservice.saveOrUpdateMerchantConfiguration(conf);
  }
  @Override
  public void deleteModule() throws Exception {
    ConfigurationResponse vo = this.getConfigurations();

    MerchantConfiguration conf =
        (MerchantConfiguration) vo.getConfiguration(PaymentConstants.PAYMENT_PAYPALNAME);

    if (conf != null) {
      MerchantService mservice =
          (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
      mservice.deleteMerchantConfiguration(conf);
    }
  }
  @Override
  public void saveModule() throws Exception {
    boolean fielderror = false;
    if (this.getKeys() == null || StringUtils.isBlank(this.getKeys().getKey1())) {
      addFieldError("keys.key1", getText("errors.required.fedexkey"));
      fielderror = true;
    }
    if (StringUtils.isBlank(this.getKeys().getUserid())) {
      addFieldError("keys.userid", getText("errors.required.userid"));
      fielderror = true;
    }
    if (StringUtils.isBlank(this.getKeys().getPassword())) {
      addFieldError("keys.password", getText("errors.required.fedexpassword"));
      fielderror = true;
    }
    if (StringUtils.isBlank(this.getKeys().getKey2())) {
      addFieldError("keys.key2", getText("errors.required.fedexmeter"));
      fielderror = true;
    }

    if (fielderror) {
      throw new ValidationException("Missing fields");
    }

    Context ctx =
        (Context) super.getServletRequest().getSession().getAttribute(ProfileConstants.context);
    Integer merchantid = ctx.getMerchantid();

    String submitedcredentials = ShippingUtil.buildShippingKeyLine(keys);

    String submitedproperties = ShippingUtil.buildShippingPropertiesLine(this.getProperties());

    String packageOption = getPackageSelection();

    List modulestosave =
        ShippingUtil.arrangeConfigurationsToSave(
            merchantid,
            configurations,
            moduleid,
            submitedcredentials,
            submitedproperties,
            packageOption,
            null,
            null);

    MerchantService mservice =
        (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
    mservice.saveOrUpdateMerchantConfigurations(modulestosave);
  }
  @RequestMapping(
      value = {"/password/reset.html"},
      method = RequestMethod.POST)
  public String resetPassword(HttpServletRequest request) throws Exception {

    String userName = request.getParameter("resetpasswordusername");
    CustomerService cservice =
        (CustomerService) ServiceFactory.getService(ServiceFactory.CustomerService);

    MerchantStore store = SessionUtil.getMerchantStore(request);
    Customer customer = cservice.findCustomerByUserName(userName, store.getMerchantId());

    if (customer != null) {
      cservice.resetCustomerPassword(customer);
    }

    super.setMessage("label.customer.passwordreset", request);

    return "redirect:/home.html";
  }
  /** Creates a new Customer */
  @WebMethod
  public @WebResult CreateCustomerWebServiceResponse createCustomer(
      @WebParam(name = "credentials") WebServiceCredentials credentials,
      @WebParam(name = "customer") Customer customer) {
    MessageSource messageSource = (MessageSource) SpringUtil.getBean("messageSource");

    Locale locale = LocaleUtil.getDefaultLocale();
    if (StringUtils.isNotBlank(customer.getCustomerLang())) {
      locale = LocaleUtil.getLocale(customer.getCustomerLang());
    }

    CreateCustomerWebServiceResponse response = new CreateCustomerWebServiceResponse();
    try {

      // check credentials
      validateCredentials(locale, credentials);

      String[] validationErrorList = validate(customer, locale, messageSource);
      if (validationErrorList != null && validationErrorList.length > 0) {
        response.setMessages(validationErrorList);
        response.setStatus(2);
        return response;
      }

      CustomerService cservice =
          (CustomerService) ServiceFactory.getService(ServiceFactory.CustomerService);

      // if customer has customer id >0 check that it belongs to this merchant id
      com.salesmanager.core.entity.customer.Customer tmpCustomer = null;
      if (customer.getCustomerId() > 0) {
        tmpCustomer = cservice.getCustomer(customer.getCustomerId());
        if (tmpCustomer != null) {
          if (tmpCustomer.getMerchantId() != credentials.getMerchantId()) {
            response.setMessages(
                new String[] {messageSource.getMessage("messages.authorization", null, locale)});
            response.setStatus(0);
          }
        }
      }

      com.salesmanager.core.entity.customer.Customer newCustomer =
          new com.salesmanager.core.entity.customer.Customer();

      if (tmpCustomer != null) { // modify existing customer
        newCustomer = tmpCustomer;
      }
      BeanUtils.copyProperties(newCustomer, customer);

      // copy properties to billing
      newCustomer.setCustomerBillingCity(customer.getCustomerCity());
      newCustomer.setCustomerBillingCountryId(customer.getCustomerCountryId());
      newCustomer.setCustomerBillingCountryName(newCustomer.getBillingCountry());
      newCustomer.setCustomerBillingFirstName(customer.getCustomerFirstname());
      newCustomer.setCustomerBillingLastName(customer.getCustomerLastname());
      newCustomer.setCustomerBillingPostalCode(customer.getCustomerPostalCode());
      newCustomer.setCustomerBillingState(newCustomer.getStateProvinceName());
      newCustomer.setCustomerBillingStreetAddress(customer.getCustomerStreetAddress());
      newCustomer.setCustomerBillingZoneId(customer.getCustomerZoneId());

      newCustomer.setLocale(locale);
      newCustomer.setMerchantId(credentials.getMerchantId());

      if (StringUtils.isBlank(customer.getZoneName()) && customer.getCustomerZoneId() > 0) {
        java.util.Map zones =
            (java.util.Map)
                RefCache.getAllZonesmap(LanguageUtil.getLanguageNumberCode(locale.getLanguage()));
        if (zones != null) {
          Zone z = (Zone) zones.get(customer.getCustomerZoneId());
          if (z != null) {
            newCustomer.setCustomerState(z.getZoneName());
          }
        }
      }

      if (StringUtils.isBlank(newCustomer.getBillingState())
          && newCustomer.getCustomerZoneId() > 0) {
        java.util.Map zones =
            (java.util.Map)
                RefCache.getAllZonesmap(LanguageUtil.getLanguageNumberCode(locale.getLanguage()));
        if (zones != null) {
          Zone z = (Zone) zones.get(newCustomer.getCustomerZoneId());
          if (z != null) {
            newCustomer.setCustomerBillingState(z.getZoneName());
          }
        }
      }

      cservice.saveOrUpdateCustomer(newCustomer, SystemUrlEntryType.WEB, locale);

      response.setMessages(
          new String[] {
            messageSource.getMessage("messages.customer.customerregistered", null, locale)
          });
      response.setStatus(1);
      response.setCustomerId(newCustomer.getCustomerId());

    } catch (Exception e) {

      if (e instanceof ServiceException) {
        String msg[] = {((ServiceException) e).getMessage()};
        response.setMessages(msg);
        response.setStatus(0);
      } else {

        log.error("Exception occurred while creating Customer", e);
        response.setMessages(
            new String[] {messageSource.getMessage("errors.technical", null, locale)});
        response.setStatus(0);
      }
    }
    return response;
  }
  @Transactional
  public boolean changeCustomerPassword(Customer customer, String oldPassword, String newPassword)
      throws Exception {
    String key = EncryptionUtil.generatekey(String.valueOf(SecurityConstants.idConstant));
    String encrypted = EncryptionUtil.encrypt(key, newPassword);

    String old = EncryptionUtil.encrypt(key, oldPassword);

    if (!customer.getCustomerPassword().equals(old)) {
      return false;
    }

    customer.setCustomerPassword(encrypted);

    MerchantService mservice =
        (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);

    // MerchantUserInformation minfo = mservice.getMerchantUserInfo(customer
    //		.getMerchantId());

    MerchantStore store = mservice.getMerchantStore(customer.getMerchantId());

    customerDao.saveOrUptade(customer);

    // send email
    String l = config.getString("core.system.defaultlanguage", "en");
    if (!StringUtils.isBlank(customer.getCustomerLang())) {
      l = customer.getCustomerLang();
    }

    LabelUtil lhelper = LabelUtil.getInstance();
    String subject = lhelper.getText(l, "label.profile.information");
    String info = lhelper.getText(l, "label.email.customer.portalinfo");
    String pass = lhelper.getText(l, "label.email.customer.passwordreset.text") + " " + newPassword;

    // @TODO replace suffix
    String url =
        "<a href=\""
            + config.getString("core.accountmanagement.portal.url")
            + "\">"
            + config.getProperty("core.accountmanagement.portal.url")
            + "</a>";
    String portalurl = lhelper.getText(l, "label.email.customer.portalurl") + " " + url;

    Map emailctx = new HashMap();
    emailctx.put("EMAIL_STORE_NAME", store.getStorename());
    emailctx.put("EMAIL_CUSTOMER_PASSWORD", pass);
    emailctx.put("EMAIL_CUSTOMER_PORTAL_INFO", info);
    emailctx.put("EMAIL_CUSTOMER_PORTAL_ENTRY", portalurl);
    emailctx.put("EMAIL_CONTACT_OWNER", store.getStoreemailaddress());

    CommonService cservice = new CommonService();

    cservice.sendHtmlEmail(
        customer.getCustomerEmailAddress(),
        subject,
        store,
        emailctx,
        "email_template_password_reset_customer.ftl",
        customer.getCustomerLang());

    return true;
  }
  /**
   * Reset a Customer password. Will also send an email the the customer with the new password
   *
   * @param customer
   * @throws Exception
   */
  @Transactional(rollbackFor = {Exception.class})
  public void resetCustomerPassword(Customer customer) throws Exception {

    MerchantService mservice =
        (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
    MerchantStore store = mservice.getMerchantStore(customer.getMerchantId());
    // MerchantUserInformation minfo = mservice.getMerchantUserInfo(customer
    //		.getMerchantId());

    if (!customer.isCustomerAnonymous()) {

      // generate password
      PasswordGeneratorModule passwordGenerator =
          (PasswordGeneratorModule) SpringUtil.getBean("passwordgenerator");

      // encrypt
      String key = EncryptionUtil.generatekey(String.valueOf(SecurityConstants.idConstant));
      boolean found = true;

      String password = null;
      String encrypted = null;
      // validate if already exist
      while (found) {

        password = passwordGenerator.generatePassword();
        encrypted = EncryptionUtil.encrypt(key, password);
        Customer cfound =
            customerDao.findByUserNameAndPassword(customer.getCustomerNick(), encrypted);
        if (cfound == null) {
          found = false;
        }
      }

      // store in customer
      customer.setCustomerNick(customer.getCustomerEmailAddress());
      customer.setCustomerPassword(encrypted);
      customerDao.saveOrUptade(customer);

      // send email
      String l = config.getString("core.system.defaultlanguage", "en");
      if (!StringUtils.isBlank(customer.getCustomerLang())) {
        l = customer.getCustomerLang();
      }

      LabelUtil lhelper = LabelUtil.getInstance();
      String subject = lhelper.getText(l, "label.profile.information");
      String info = lhelper.getText(l, "label.email.customer.portalinfo");
      String pass = lhelper.getText(l, "label.email.customer.passwordreset.text") + " " + password;

      // @TODO replace suffix
      String url =
          "<a href=\""
              + config.getString("core.accountmanagement.portal.url")
              + "\">"
              + config.getString("core.accountmanagement.portal.url")
              + "</a>";
      String portalurl = lhelper.getText(l, "label.email.customer.portalurl") + " " + url;

      Map emailctx = new HashMap();
      emailctx.put("EMAIL_STORE_NAME", store.getStorename());
      emailctx.put("EMAIL_CUSTOMER_PASSWORD", pass);
      emailctx.put("EMAIL_CUSTOMER_PORTAL_INFO", info);
      emailctx.put("EMAIL_CONTACT_OWNER", store.getStoreemailaddress());

      CommonService cservice = new CommonService();
      cservice.sendHtmlEmail(
          customer.getCustomerEmailAddress(),
          subject,
          store,
          emailctx,
          "email_template_password_reset_customer.ftl",
          customer.getCustomerLang());
    }
  }
  @Transactional(rollbackFor = {Exception.class})
  public void saveOrUpdateCustomer(Customer customer, SystemUrlEntryType entryType, Locale locale)
      throws Exception {

    MerchantService mservice =
        (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);

    MerchantStore store = mservice.getMerchantStore(customer.getMerchantId());
    // MerchantUserInformation minfo = mservice.getMerchantUserInfo(customer
    //		.getMerchantId());

    if (entryType == null) {
      entryType = SystemUrlEntryType.WEB;
    }

    // check if email aleady exist

    boolean isNew = false;
    if (customer.getCustomerId() == 0) {
      isNew = true;
    }

    if (isNew && !customer.isCustomerAnonymous()) {

      // generate password
      PasswordGeneratorModule passwordGenerator =
          (PasswordGeneratorModule) SpringUtil.getBean("passwordgenerator");

      // encrypt
      String key = EncryptionUtil.generatekey(String.valueOf(SecurityConstants.idConstant));
      boolean found = true;

      String password = null;
      String encrypted = null;
      // validate if already exist
      while (found) {

        password = passwordGenerator.generatePassword();
        encrypted = EncryptionUtil.encrypt(key, password);
        Customer cfound =
            customerDao.findByUserNameAndPassword(customer.getCustomerNick(), encrypted);
        if (cfound == null) {
          found = false;
        }
      }

      // store in customer
      customer.setCustomerNick(customer.getCustomerEmailAddress());
      customer.setCustomerPassword(encrypted);

      // send email
      String l = config.getString("core.system.defaultlanguage", "en");
      if (!StringUtils.isBlank(customer.getCustomerLang())) {
        l = customer.getCustomerLang();
      }

      LabelUtil lhelper = LabelUtil.getInstance();
      String subject = lhelper.getText(l, "label.profile.information");
      List params = new ArrayList();
      params.add(store.getStorename());
      String greeting = lhelper.getText(locale, "label.email.customer.greeting", params);

      String username =
          lhelper.getText(l, "label.generic.customer.username") + " " + customer.getCustomerNick();
      String pass = lhelper.getText(l, "label.generic.customer.password") + " " + password;

      String info = "";
      String portalurl = "";

      if (entryType == SystemUrlEntryType.PORTAL) {
        info = lhelper.getText(l, "label.email.customer.portalinfo");
        String url =
            "<a href=\""
                + config.getProperty("core.accountmanagement.portal.url")
                + "/"
                + customer.getMerchantId()
                + "\">"
                + config.getProperty("core.accountmanagement.portal.url")
                + "/"
                + customer.getMerchantId()
                + "</a>";
        portalurl = lhelper.getText(l, "label.email.customer.portalurl") + " " + url;
      } else {
        info = lhelper.getText(l, "label.email.customer.webinfo");
        String url =
            "<a href=\""
                + ReferenceUtil.buildCatalogUri(store)
                + "/\">"
                + ReferenceUtil.buildCatalogUri(store)
                + "/landing.action?merchantId="
                + store.getMerchantId()
                + "</a>";
        portalurl = lhelper.getText(l, "label.email.customer.weburl") + " " + url;
      }

      Map emailctx = new HashMap();
      emailctx.put("EMAIL_STORE_NAME", store.getStorename());
      emailctx.put("EMAIL_CUSTOMER_FIRSTNAME", customer.getCustomerFirstname());
      emailctx.put("EMAIL_CUSTOMER_LAST", customer.getCustomerLastname());
      emailctx.put("EMAIL_CUSTOMER_USERNAME", username);
      emailctx.put("EMAIL_CUSTOMER_PASSWORD", pass);
      emailctx.put("EMAIL_GREETING", greeting);
      emailctx.put("EMAIL_CUSTOMER_PORTAL_INFO", info);
      emailctx.put("EMAIL_CUSTOMER_PORTAL_ENTRY", portalurl);
      emailctx.put("EMAIL_CONTACT_OWNER", store.getStoreemailaddress());

      CommonService cservice = new CommonService();
      cservice.sendHtmlEmail(
          customer.getCustomerEmailAddress(),
          subject,
          store,
          emailctx,
          "email_template_customer.ftl",
          customer.getCustomerLang());
    }

    customerDao.saveOrUptade(customer);

    // set CustomerInfo

    CustomerInfo customerInfo = new CustomerInfo();
    customerInfo.setCustomerInfoId(customer.getCustomerId());

    int login = customerInfo.getCustomerInfoNumberOfLogon();
    customerInfo.setCustomerInfoNumberOfLogon(login++);
    customerInfo.setCustomerInfoDateOfLastLogon(new Date());
    customerInfoDao.saveOrUpdate(customerInfo);
  }
Example #13
0
  /** Complete overwrite * */
  public String comitOrder() {

    try {

      boolean paymentProcessed = false;

      // Get all entities

      Order order = SessionUtil.getOrder(getServletRequest());
      MerchantStore store = SessionUtil.getMerchantStore(getServletRequest());

      PaymentMethod payment = SessionUtil.getPaymentMethod(getServletRequest());

      order.setPaymentMethod(payment.getPaymentMethodName());
      order.setPaymentModuleCode(payment.getPaymentModuleName());

      Customer customer = SessionUtil.getCustomer(getServletRequest());

      if (super.getServletRequest().getSession().getAttribute("TRANSACTIONCOMITED") != null) {
        addActionError(
            getText(
                "error.transaction.duplicate",
                new String[] {String.valueOf(order.getOrderId()), store.getStoreemailaddress()}));
        return "GENERICERROR";
      }

      OrderService oservice = (OrderService) ServiceFactory.getService(ServiceFactory.OrderService);

      try {

        Map orderProducts = SessionUtil.getOrderProducts(getServletRequest());
        Set s = new HashSet();

        for (Object o : orderProducts.values()) {

          OrderProduct op = (OrderProduct) o;
          s.add(op);
        }

        order.setOrderProducts(s);

        String comments = null;
        if (this.getOrderHistory() != null) {
          comments = this.getOrderHistory().getComments();
        }

        // Order, PaymentMethod,
        ProcessorContext context = new ProcessorContext();

        Collection files = oservice.getOrderProductDownloads(order.getOrderId());
        if (files != null && files.size() > 0) {
          context.addObject("files", files);
        }

        context.addObject("Order", order);
        context.addObject("Customer", customer);
        context.addObject("MerchantStore", store);
        context.addObject("PaymentMethod", payment);
        context.addObject("Locale", super.getLocale());
        context.addObject("comments", comments);
        context.addObject("products", orderProducts.values());

        WorkflowProcessor wp = (WorkflowProcessor) SpringUtil.getBean("invoiceWorkflow");
        wp.doWorkflow(context);

        paymentProcessed = true;

        // set an indicator in HTTPSession to prevent duplicates
        super.getServletRequest().getSession().setAttribute("TRANSACTIONCOMITED", "true");

        if (!StringUtils.isBlank(comments)) {
          SessionUtil.setOrderStatusHistory(this.getOrderHistory(), getServletRequest());
        }

      } catch (Exception e) {
        if (e instanceof TransactionException) {
          super.addErrorMessage("error.payment.paymenterror");
          return "PAYMENTERROR";
        }

        if (e instanceof OrderException) {
          try {
            oservice.sendOrderProblemEmail(order.getMerchantId(), order, customer, store);
          } catch (Exception ee) {
            log.error(ee);
          }
        }

        addActionError(
            getText(
                "message.error.comitorder.error",
                new String[] {String.valueOf(order.getOrderId()), store.getStoreemailaddress()}));
        log.error(e);
        return "GENERICERROR";
      }

      return SUCCESS;

    } catch (Exception e) {
      log.error(e);
    }

    return SUCCESS;
  }
Example #14
0
public class SubscriptionAction extends CheckoutBaseAction
    implements ModelDriven<CheckoutParams>, Constants {
  private static final long serialVersionUID = 1L;
  private Logger log = Logger.getLogger(SubscriptionAction.class);

  private Map paymentMethods;
  private Collection creditCards;
  private CheckoutParams value = new CheckoutParams();

  // combo box
  private Collection<Country> countries;
  private Collection<Zone> zonesByCountry = new ArrayList();
  private String zone;

  private String storeCountry;
  private String billingState;
  // private int selectedCountryId;

  private CatalogService cservice =
      (CatalogService) ServiceFactory.getService(ServiceFactory.CatalogService);
  private MerchantService mservice =
      (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
  private OrderService oservice =
      (OrderService) ServiceFactory.getService(ServiceFactory.OrderService);

  MerchantStore store = null;

  private Customer customer; // submited
  private String confirmEmailAddress;
  private String confirmPassword;
  private String customerBillingStreetAddress1;
  private String customerBillingStreetAddress2;

  private PaymentMethod paymentMethod; // submited

  private String formstate;

  private void preparePage() throws Exception {

    Map ccmap = com.salesmanager.core.service.cache.RefCache.getSupportedCreditCards();
    if (ccmap != null) {
      creditCards = new ArrayList();
      Iterator i = ccmap.keySet().iterator();

      while (i.hasNext()) {
        int key = (Integer) i.next();
        creditCards.add((CentralCreditCard) ccmap.get(key));
      }
    }

    paymentMethods = PaymentUtil.getPaymentMethods(1, super.getLocale());

    // too complex to be handled with webwork, will store the object in http
    super.getServletRequest().setAttribute("PAYMENTS", paymentMethods);
  }

  public CheckoutParams getModel() {
    return value;
  }

  // goes to summary page
  public String subscribe() {

    try {

      preparePage();
      validateCustomer();

      SessionUtil.setCustomer(customer, getServletRequest());

      prepareZones();

      if (this.getPaymentMethod() == null
          || this.getPaymentMethod().getPaymentModuleName() == null) {
        super.addActionError("error.nopaymentmethod");
        return INPUT;
      }

      super.getServletRequest().setAttribute("SELECTEDPAYMENT", this.getPaymentMethod());

      MerchantStore store = SessionUtil.getMerchantStore(getServletRequest());

      // check if payment method is credit card type
      if (com.salesmanager.core.util.PaymentUtil.isPaymentModuleCreditCardType(
          this.getPaymentMethod().getPaymentModuleName())) {
        super.validateCreditCard(this.getPaymentMethod(), store.getMerchantId());
      } else {
        super.setCreditCard(null); // reset credit card information
      }

      if (getFieldErrors().size() > 0) {
        return INPUT;
      }

      SessionUtil.setPaymentMethod(this.getPaymentMethod(), getServletRequest());

    } catch (Exception e) {
      log.error(e);
      super.addActionError(getText("error.process.notransaction"));
      return "GLOBALERROR";
    }

    return SUCCESS;
  }

  public void validateCustomer() {

    if (StringUtils.isBlank(customer.getCustomerEmailAddress())) {
      addFieldError("customer.customerEmailAddress", getText("messages.required.email"));
      super.addFieldMessage("customer.customerEmailAddress", "messages.required.email");
    } else {
      if (!CustomerUtil.validateEmail(customer.getCustomerEmailAddress())) {
        addFieldError("customer.customerEmailAddress", getText("messages.invalid.email"));
        super.addFieldMessage("customer.customerEmailAddress", "messages.invalid.email");
      }
    }
    /*
     * if(StringUtils.isBlank(customer.getCustomerPassword())) {
     * addFieldError("customer.customerPassword",
     * getText("messages.required.password")); }
     * if(StringUtils.isBlank(getConfirmEmailAddress())) {
     * addFieldError("confirmEmailAddress",
     * getText("messages.required.email.confirm")); }else{
     * if(!getConfirmEmailAddress
     * ().equals(customer.getCustomerEmailAddress())){
     * addFieldError("confirmEmailAddress",
     * getText("messages.unequal.email.confirm")); } }
     * if(StringUtils.isBlank(getConfirmPassword())) {
     * addFieldError("confirmPassword",
     * getText("messages.required.password.confirm")); }else{
     * if(!getConfirmPassword().equals(customer.getCustomerPassword())){
     * addFieldError("confirmPassword",
     * getText("messages.unequal.password.confirm")); } }
     */
    if (StringUtils.isBlank(customer.getCustomerFirstname())) {
      addFieldError("customer.customerFirstname", getText("messages.required.firstname"));
      super.addFieldMessage("customer.customerFirstname", "messages.required.firstname");
    }
    if (StringUtils.isBlank(customer.getCustomerLastname())) {
      addFieldError("customer.customerLastname", getText("messages.required.lastname"));
      super.addFieldMessage("customer.customerLastname", "messages.required.lastname");
    }
    if (StringUtils.isBlank(customer.getCustomerBillingStreetAddress())) {
      addFieldError(
          "customer.customerBillingStreetAddress", getText("messages.required.streetaddress"));
      super.addFieldMessage(
          "customer.customerBillingStreetAddress", "messages.required.streetaddress");
    }
    if (StringUtils.isBlank(customer.getCustomerBillingCity())) {
      addFieldError("customer.customerBillingCity", getText("messages.required.city"));
      super.addFieldMessage("customer.customerBillingCity", "messages.required.city");
    }
    if (!StringUtils.isBlank(this.getFormstate()) && this.getFormstate().equals("text")) {
      if (StringUtils.isBlank(customer.getCustomerBillingState())) {
        addFieldError("customer.customerBillingState", getText("messages.required.stateprovince"));
        super.addFieldMessage("customer.customerBillingState", "messages.required.stateprovince");
      }
    }
    if (StringUtils.isBlank(customer.getCustomerBillingPostalCode())) {
      addFieldError("customer.customerBillingPostalCode", getText("messages.required.postalcode"));
      super.addFieldMessage("customer.customerBillingPostalCode", "messages.required.postalcode");
    }

    if (StringUtils.isBlank(customer.getCustomerTelephone())) {
      addFieldError("customer.customerTelephone", getText("messages.required.phone"));
      super.addFieldMessage("customer.customerTelephone", "messages.required.phone");
    }
    /**
     * else if(!CustomerUtil.ValidatePhoneNumber(customer.getCustomerTelephone ())){
     * addFieldError("customer.customerTelephone", getText("messages.invalid.phone"));
     * super.addFieldMessage("customer.customerTelephone", "messages.invalid.phone"); }
     */
    String cName = "";
    Map lcountries = RefCache.getCountriesMap();
    if (lcountries != null) {
      Country country = (Country) lcountries.get(customer.getCustomerBillingCountryId());
      Set descriptions = country.getDescriptions();
      if (descriptions != null) {
        Iterator cIterator = descriptions.iterator();
        while (cIterator.hasNext()) {
          CountryDescription desc = (CountryDescription) cIterator.next();
          cName = desc.getCountryName();
          if (desc.getId().getLanguageId()
              == LanguageUtil.getLanguageNumberCode(super.getLocale().getLanguage())) {
            cName = desc.getCountryName();
            break;
          }
        }
      }
    }

    if (StringUtils.isBlank(customer.getCustomerBillingState())) {
      Map lzones =
          RefCache.getAllZonesmap(
              LanguageUtil.getLanguageNumberCode(super.getLocale().getLanguage()));
      if (lzones != null) {
        Zone z = (Zone) lzones.get(customer.getCustomerBillingZoneId());
        if (z != null) {
          customer.setCustomerBillingState(z.getZoneName());
          customer.setCustomerState(z.getZoneName());
        }
      }
    }

    String lang = super.getLocale().getLanguage();

    customer.setCountryName(cName);
    customer.setCustomerBillingCountryName(cName);
    customer.setCustomerLang(lang);

    customer.setCountryName(customer.getBillingCountry());
    customer.setCustomerCity(customer.getCustomerBillingCity());
    customer.setCustomerCountryId(customer.getCustomerBillingCountryId());
    customer.setCustomerLang(super.getLocale().getLanguage());
    customer.setCustomerPostalCode(customer.getCustomerBillingPostalCode());
    customer.setCustomerStreetAddress(customer.getCustomerBillingStreetAddress());
    customer.setCustomerState(customer.getBillingState());
    customer.setCustomerZoneId(customer.getCustomerBillingZoneId());
  }

  /**
   * Invoked after addSubscriptionItem
   *
   * @throws Exception
   */
  public void addItem() throws Exception {

    boolean quantityUpdated = false;

    // get store country
    Map lcountries =
        RefCache.getAllcountriesmap(LanguageUtil.getLanguageNumberCode(value.getLang()));
    if (lcountries != null) {
      Country country = (Country) lcountries.get(store.getCountry());
      getServletRequest().getSession().setAttribute("COUNTRY", country);
    }

    // check if language is supported by the store
    if (lcountries != null) {
      Country country = (Country) lcountries.get(store.getCountry());
      getServletRequest().getSession().setAttribute("COUNTRY", country);
    }

    // store can not be null, if it is the case, generic error page
    if (store == null) {
      throw new Exception("Invalid Store!");
    }

    // check if order product already exist. If that orderproduct already
    // exist
    // and has no ptoperties, so just update the quantity
    if (value.getAttributeId() == null
        || (value.getAttributeId() != null && value.getAttributeId().size() == 0)) {
      Map savedProducts = SessionUtil.getOrderProducts(getServletRequest());
      if (savedProducts != null) {
        Iterator it = savedProducts.keySet().iterator();
        while (it.hasNext()) {
          String line = (String) it.next();
          OrderProduct op = (OrderProduct) savedProducts.get(line);
          if (op.getProductId() == value.getProductId()) {
            Set attrs = op.getOrderattributes();
            if (attrs.size() == 0) {
              int qty = op.getProductQuantity();
              qty = qty + value.getQty();
              op.setProductQuantity(qty);
              quantityUpdated = true;
              break;
            }
          }
        }
      }
    }

    // create an order with merchantId and all dates
    // will need to create a new order id when submited
    Order order = SessionUtil.getOrder(getServletRequest());
    if (order == null) {
      order = new Order();
    }

    order.setMerchantId(store.getMerchantId());
    order.setDatePurchased(new Date());
    SessionUtil.setOrder(order, getServletRequest());

    if (!StringUtils.isBlank(value.getReturnUrl())) {
      // Return to merchant site Url is set from store.
      value.setReturnUrl(store.getContinueshoppingurl());
    }
    SessionUtil.setMerchantStore(store, getServletRequest());

    if (!quantityUpdated) { // new submission

      // Prepare order
      OrderProduct orderProduct =
          com.salesmanager.core.util.CheckoutUtil.createOrderProduct(
              value.getProductId(), getLocale(), store.getCurrency());
      orderProduct.setProductQuantity(value.getQty());
      orderProduct.setProductId(value.getProductId());

      List<OrderProductAttribute> attributes = new ArrayList<OrderProductAttribute>();
      if (value.getAttributeId() != null && value.getAttributeId().size() > 0) {
        for (Long attrId : value.getAttributeId()) {
          if (attrId != null && attrId != 0) {
            ProductAttribute pAttr =
                cservice.getProductAttributeByOptionValueAndProduct(value.getProductId(), attrId);
            if (pAttr != null && pAttr.getProductId() == value.getProductId()) {
              OrderProductAttribute orderAttr = new OrderProductAttribute();
              orderAttr.setProductOptionValueId(pAttr.getOptionValueId());

              attributes.add(orderAttr);
            } else {
              LogMerchantUtil.log(
                  value.getMerchantId(),
                  getText(
                      "error.validation.product.attributes.ids",
                      new String[] {String.valueOf(attrId), String.valueOf(value.getProductId())}));
            }
          }
        }
      }

      if (!attributes.isEmpty()) {
        // ShoppingCartUtil.addAttributesFromRawObjects(attributes,
        // orderProduct, store.getCurrency(), getServletRequest());
        com.salesmanager.core.util.CheckoutUtil.addAttributesToProduct(
            attributes, orderProduct, store.getCurrency(), getLocale());
      }

      Set attributesSet = new HashSet(attributes);
      orderProduct.setOrderattributes(attributesSet);

      SessionUtil.addOrderProduct(orderProduct, getServletRequest());
    }

    // because this is a submission, cannot continue browsing, so that's it
    // for the OrderProduct
    Map orderProducts = SessionUtil.getOrderProducts(super.getServletRequest());
    // transform to a list
    List products = new ArrayList();

    if (orderProducts != null) {
      Iterator i = orderProducts.keySet().iterator();
      while (i.hasNext()) {
        String line = (String) i.next();
        OrderProduct op = (OrderProduct) orderProducts.get(line);
        products.add(op);
      }
      super.getServletRequest().getSession().setAttribute("ORDER_PRODUCT_LIST", products);
    }

    // for displaying the order summary, need to create an OrderSummary
    // entity
    OrderTotalSummary summary =
        oservice.calculateTotal(order, products, store.getCurrency(), super.getLocale());

    Map totals =
        OrderUtil.getOrderTotals(
            order.getOrderId(), summary, store.getCurrency(), super.getLocale());

    HttpSession session = getServletRequest().getSession();

    // transform totals to a list
    List totalsList = new ArrayList();
    if (totals != null) {
      Iterator totalsIterator = totals.keySet().iterator();
      while (totalsIterator.hasNext()) {
        String key = (String) totalsIterator.next();
        OrderTotal total = (OrderTotal) totals.get(key);
        totalsList.add(total);
      }
    }

    SessionUtil.setOrderTotals(totalsList, getServletRequest());

    value.setLangId(LanguageUtil.getLanguageNumberCode(value.getLang()));
    prepareZones();

    // set locale according to the language passed in parameters and store
    // information
    Locale locale = LocaleUtil.getLocaleFromStoreEntity(store, value.getLang());
    setLocale(locale);
  }

  private void prepareZones() {

    if (value != null && value.getProductId() > 0) {
      setCountries(RefUtil.getCountries(value.getLang()));

      if (this.customer == null) {

        customer = SessionUtil.getCustomer(getServletRequest());

        if (customer == null) {

          customer = new Customer();
          customer.setCustomerBillingCountryId(value.getCountryId());
        }
      }

      customer.setLocale(getLocale());

      SessionUtil.setCustomer(customer, getServletRequest());

      Collection zones =
          RefUtil.getZonesByCountry(customer.getCustomerBillingCountryId(), value.getLang());

      if (zones != null && zones.size() > 0) {
        setZonesByCountry(zones);
      } else {
        setZone(customer.getBillingState());
      }

    } else {

      if (this.customer == null) {

        customer = SessionUtil.getCustomer(getServletRequest());
      }
      if (customer != null) {

        customer.setLocale(super.getLocale());

        setCountries(RefUtil.getCountries(super.getLocale().getLanguage()));

        Collection zones =
            RefUtil.getZonesByCountry(
                customer.getCustomerBillingCountryId(),
                LocaleUtil.getDefaultLocale().getLanguage());

        if (zones != null && zones.size() > 0) {
          setZonesByCountry(zones);
        } else {
          setZone(customer.getBillingState());
        }
      } else {

        setCountries(RefUtil.getCountries(LocaleUtil.getDefaultLocale().getLanguage()));

        Configuration conf = PropertiesUtil.getConfiguration();
        int defaultCountry = conf.getInt("core.system.defaultcountryid");
        customer = new Customer();
        customer.setCustomerBillingCountryId(defaultCountry);
        customer.setLocale(super.getLocale());

        Collection zones =
            RefUtil.getZonesByCountry(
                customer.getCustomerBillingCountryId(),
                LocaleUtil.getDefaultLocale().getLanguage());

        if (zones != null && zones.size() > 0) {
          setZonesByCountry(zones);
        } else {
          setZone(customer.getBillingState());
        }

        SessionUtil.setCustomer(customer, getServletRequest());
      }
    }
  }

  /**
   * This methhod is for subscription step 1
   *
   * @return
   */
  public String displaySubscriptionForm() {

    try {

      // check if the session is still active
      Order o = SessionUtil.getOrder(getServletRequest());
      if (o == null) {
        super.addActionError(getText("error.sessionexpired"));
        return "GLOBALERROR";
      }

      // This is for the progress bar
      getServletRequest().setAttribute("STEP", "1");
      prepareZones();

      /*
       * //STUB CUSTOMER
       * customer=ShoppingCartUtil.getCustomer(getServletRequest());
       * customer.setCustomerEmailAddress("*****@*****.**");
       * customer.setCustomerFirstname("Carlito");
       * customer.setCustomerLastname("Samsonos");
       * customer.setCustomerBillingStreetAddress("358 Du Languedoc");
       * customer.setCustomerBillingCity("Boucherville");
       * customer.setCustomerBillingState("Quebec");
       * customer.setCustomerBillingZoneId(76);
       * customer.setCustomerBillingCountryId(38);
       * customer.setCustomerBillingPostalCode("J4B8J9");
       * customer.setCustomerTelephone("4504497181");
       * ShoppingCartUtil.setCustomer(customer, getServletRequest());
       */

      preparePage();
      return SUCCESS;
    } catch (Exception e) {
      super.addActionError(getText("error.process.notransaction"));
      log.error(e);
      return "GLOBALERROR";
    }
  }

  /**
   * This is the main entry point to the subscription process. In this case Only one item can be
   * added to the subscription process. Once the product added, the method displaySubscriptionForm
   * is invoked
   *
   * @return
   */
  public String addSubscriptionItem() {

    try {

      if (!validateAddSubscription()) {
        return INPUT;
      }

      addItem();
      return SUCCESS;

    } catch (Exception e) {
      log.error(e);
      return "GLOBALERROR";
    }
  }

  /**
   * Validates input parameters for a new subscription request
   *
   * @return
   */
  public boolean validateAddSubscription() {
    boolean success = true;
    if (value.getMerchantId() == 0) {
      addActionError(
          getText("error.validation.parameter.missing", new String[] {MERCHANT_ID_PARAM}));
      success = false;
    }
    if (value.getProductId() == 0) {
      addActionError(
          getText("error.validation.parameter.missing", new String[] {PRODUCT_ID_PARAM}));
      success = false;
    }

    if (success) {
      try {

        store = mservice.getMerchantStore(value.getMerchantId());
        Collection<MerchantUserInformation> minfo =
            mservice.getMerchantUserInfo(value.getMerchantId());

        if (store == null) {
          addActionError(
              getText(
                  "error.merchant.unavailable",
                  new String[] {String.valueOf(value.getMerchantId())}));
          return false;
        }

        // maybe this has to be done
        value.setCountryId(store.getCountry());

        // @TODO log to CommonService
        Product product = cservice.getProduct(value.getProductId());
        if (product == null || product.getMerchantId() != value.getMerchantId()) {
          LogMerchantUtil.log(
              value.getMerchantId(),
              getText(
                  "error.validation.merchant.product.ids",
                  new String[] {
                    String.valueOf(value.getProductId()), String.valueOf(value.getMerchantId())
                  }));
          addActionError(
              getText(
                  "error.validation.merchant.product.ids",
                  new String[] {
                    String.valueOf(value.getProductId()), String.valueOf(value.getMerchantId())
                  }));
          success = false;
        } else {
          if (product.getProductDateAvailable().after(new Date())) {
            LogMerchantUtil.log(
                value.getMerchantId(),
                getText(
                    "error.product.unavailable.purchase",
                    new String[] {String.valueOf(value.getProductId())}));
            addActionError(
                getText(
                    "error.product.unavailable.purchase",
                    new String[] {String.valueOf(value.getProductId())}));
            success = false;
          }
          if (product.getProductQuantity() == OUT_OF_STOCK_PRODUCT_QUANTITY) {
            LogMerchantUtil.log(
                value.getMerchantId(),
                getText(
                    "error.product.unavailable.purchase",
                    new String[] {String.valueOf(value.getProductId())}));
            addActionError(
                getText(
                    "error.product.unavailable.purchase",
                    new String[] {String.valueOf(value.getProductId())}));

            Configuration config = PropertiesUtil.getConfiguration();

            // MerchantProfile profile =
            // mservice.getMerchantProfile(value.getMerchantId());

            String l = config.getString("core.system.defaultlanguage", "en");

            if (minfo == null) {
              log.error("MerchantUserInformation is null for merchantId " + value.getMerchantId());
              addActionError(
                  getText(
                      "error.product.unavailable.purchase",
                      new String[] {String.valueOf(value.getProductId())}));
              // goto global error
              throw new Exception("Invalid MerchantId,Unable to find MerchantProfile");
            }

            MerchantUserInformation user = (MerchantUserInformation) ((List) minfo).get(0);

            if (!StringUtils.isBlank(user.getUserlang())) {
              l = user.getUserlang();
            }

            String description = "";

            Collection descriptionslist = product.getDescriptions();
            if (descriptionslist != null) {
              Iterator i = descriptionslist.iterator();
              while (i.hasNext()) {
                Object o = i.next();
                if (o instanceof ProductDescription) {
                  ProductDescription desc = (ProductDescription) o;
                  description = desc.getProductName();
                  if (desc.getId().getLanguageId() == LanguageUtil.getLanguageNumberCode(l)) {
                    description = desc.getProductName();
                    break;
                  }
                }
              }
            }

            List params = new ArrayList();
            params.add(description);
            params.add(product.getProductId());

            LabelUtil lhelper = LabelUtil.getInstance();
            String subject =
                lhelper.getText(super.getLocale(), "label.email.store.outofstock.subject");
            String productId =
                lhelper.getText(super.getLocale(), "label.email.store.outofstock.product", params);

            Map emailctx = new HashMap();
            emailctx.put("EMAIL_STORE_NAME", store.getStorename());
            emailctx.put("EMAIL_PRODUCT_TEXT", productId);

            CommonService cservice = new CommonService();
            cservice.sendHtmlEmail(
                store.getStoreemailaddress(),
                subject,
                store,
                emailctx,
                "email_template_outofstock.ftl",
                store.getDefaultLang());

            success = false;

          } else if (product.getProductQuantity() < LOW_STOCK_PRODUCT_QUANTITY) {

            Configuration config = PropertiesUtil.getConfiguration();

            // MerchantProfile profile =
            // mservice.getMerchantProfile(value.getMerchantId());

            String l = config.getString("core.system.defaultlanguage", "en");

            if (minfo == null) {
              log.error("MerchantUserInformationis null for merchantId " + value.getMerchantId());
              addActionError(
                  getText(
                      "error.product.unavailable.purchase",
                      new String[] {String.valueOf(value.getProductId())}));
              // goto global error
              throw new Exception("Invalid MerchantId,Unable to find MerchantProfile");
            }

            MerchantUserInformation user = (MerchantUserInformation) ((List) minfo).get(0);

            if (!StringUtils.isBlank(user.getUserlang())) {
              l = user.getUserlang();
            }

            String description = "";

            Collection descriptionslist = product.getDescriptions();
            if (descriptionslist != null) {
              Iterator i = descriptionslist.iterator();
              while (i.hasNext()) {
                Object o = i.next();
                if (o instanceof ProductDescription) {
                  ProductDescription desc = (ProductDescription) o;
                  description = desc.getProductName();
                  if (desc.getId().getLanguageId() == LanguageUtil.getLanguageNumberCode(l)) {
                    description = desc.getProductName();
                    break;
                  }
                }
              }
            }

            List params = new ArrayList();
            params.add(description);
            params.add(product.getProductId());

            LabelUtil lhelper = LabelUtil.getInstance();
            String subject = lhelper.getText(l, "label.email.store.lowinventory.subject");
            String productId =
                lhelper.getText(
                    super.getLocale(), "label.email.store.lowinventory.product", params);

            Map emailctx = new HashMap();
            emailctx.put("EMAIL_STORE_NAME", store.getStorename());
            emailctx.put("EMAIL_PRODUCT_TEXT", productId);

            CommonService cservice = new CommonService();
            cservice.sendHtmlEmail(
                store.getStoreemailaddress(),
                subject,
                store,
                emailctx,
                "email_template_lowstock.ftl",
                store.getDefaultLang());
          }
        }

      } catch (Exception e) {
        log.error("Exception occurred while getting product by Id", e);
        addActionError(getText("errors.technical"));
      }
    }

    return success;
  }

  public Map getPaymentMethods() {
    return paymentMethods;
  }

  public void setPaymentMethods(Map paymentMethods) {
    this.paymentMethods = paymentMethods;
  }

  public Collection<Country> getCountries() {
    return countries;
  }

  public void setCountries(Collection<Country> countries) {
    this.countries = countries;
  }

  public Collection<Zone> getZonesByCountry() {
    return zonesByCountry;
  }

  public void setZonesByCountry(Collection<Zone> zonesByCountry) {
    this.zonesByCountry = zonesByCountry;
  }

  public String getConfirmEmailAddress() {
    return confirmEmailAddress;
  }

  public void setConfirmEmailAddress(String confirmEmailAddress) {
    this.confirmEmailAddress = confirmEmailAddress;
  }

  public String getConfirmPassword() {
    return confirmPassword;
  }

  public void setConfirmPassword(String confirmPassword) {
    this.confirmPassword = confirmPassword;
  }

  public Customer getCustomer() {
    return customer;
  }

  public void setCustomer(Customer customer) {
    this.customer = customer;
  }

  public String getCustomerBillingStreetAddress1() {
    return customerBillingStreetAddress1;
  }

  public void setCustomerBillingStreetAddress1(String customerBillingStreetAddress1) {
    this.customerBillingStreetAddress1 = customerBillingStreetAddress1;
  }

  public String getCustomerBillingStreetAddress2() {
    return customerBillingStreetAddress2;
  }

  public void setCustomerBillingStreetAddress2(String customerBillingStreetAddress2) {
    this.customerBillingStreetAddress2 = customerBillingStreetAddress2;
  }

  public String getStoreCountry() {
    return storeCountry;
  }

  public void setStoreCountry(String storeCountry) {
    this.storeCountry = storeCountry;
  }

  public Collection getCreditCards() {
    return creditCards;
  }

  public void setCreditCards(Collection creditCards) {
    this.creditCards = creditCards;
  }

  public PaymentMethod getPaymentMethod() {
    return paymentMethod;
  }

  public void setPaymentMethod(PaymentMethod paymentMethod) {
    this.paymentMethod = paymentMethod;
  }

  public String getBillingState() {
    return billingState;
  }

  public void setBillingState(String billingState) {
    this.billingState = billingState;
  }

  public String getZone() {
    return zone;
  }

  public void setZone(String zone) {
    this.zone = zone;
  }

  public String getFormstate() {
    return formstate;
  }

  public void setFormstate(String formstate) {
    this.formstate = formstate;
  }
}
  public Collection<ShippingOption> getShippingQuote(
      ConfigurationResponse config,
      BigDecimal orderTotal,
      Collection<PackageDetail> packages,
      Customer customer,
      MerchantStore store,
      Locale locale) {

    BigDecimal total = orderTotal;

    if (packages == null) {
      return null;
    }

    // only applies to Canada and US
    if (customer.getCustomerCountryId() != 38 && customer.getCustomerCountryId() != 223) {
      return null;
    }

    // supports en and fr
    String language = locale.getLanguage();
    if (!language.equals(Constants.FRENCH_CODE) && !language.equals(Constants.ENGLISH_CODE)) {
      language = Constants.ENGLISH_CODE;
    }

    // get canadapost credentials
    if (config == null) {
      log.error(
          "CanadaPostQuotesImp.getShippingQuote requires ConfigurationVO for key SHP_RT_CRED");
      return null;
    }

    // if store is not CAD
    if (!store.getCurrency().equals(Constants.CURRENCY_CODE_CAD)) {
      total =
          CurrencyUtil.convertToCurrency(total, store.getCurrency(), Constants.CURRENCY_CODE_CAD);
    }

    PostMethod httppost = null;

    CanadaPostParsedElements canadaPost = null;

    try {

      int icountry = store.getCountry();
      String country = CountryUtil.getCountryIsoCodeById(icountry);

      ShippingService sservice =
          (ShippingService) ServiceFactory.getService(ServiceFactory.ShippingService);
      CoreModuleService cms = sservice.getRealTimeQuoteShippingService(country, "canadapost");

      IntegrationKeys keys = (IntegrationKeys) config.getConfiguration("canadapost-keys");
      IntegrationProperties props =
          (IntegrationProperties) config.getConfiguration("canadapost-properties");

      if (cms == null) {
        // throw new
        // Exception("Central integration services not configured for "
        // + PaymentConstants.PAYMENT_PSIGATENAME + " and country id " +
        // origincountryid);
        log.error("CoreModuleService not configured for  canadapost and country id " + icountry);
        return null;
      }

      String host = cms.getCoreModuleServiceProdDomain();
      String protocol = cms.getCoreModuleServiceProdProtocol();
      String port = cms.getCoreModuleServiceProdPort();
      String url = cms.getCoreModuleServiceProdEnv();
      if (props.getProperties1().equals(String.valueOf(ShippingConstants.TEST_ENVIRONMENT))) {
        host = cms.getCoreModuleServiceDevDomain();
        protocol = cms.getCoreModuleServiceDevProtocol();
        port = cms.getCoreModuleServiceDevPort();
        url = cms.getCoreModuleServiceDevEnv();
      }

      // accept KG and CM

      StringBuffer request = new StringBuffer();

      request.append("<?xml version=\"1.0\" ?>");
      request.append("<eparcel>");
      request.append("<language>").append(language).append("</language>");

      request.append("<ratesAndServicesRequest>");
      request.append("<merchantCPCID>").append(keys.getUserid()).append("</merchantCPCID>");
      request
          .append("<fromPostalCode>")
          .append(
              com.salesmanager.core.util.ShippingUtil.trimPostalCode(store.getStorepostalcode()))
          .append("</fromPostalCode>");
      request.append("<turnAroundTime>").append("24").append("</turnAroundTime>");
      request
          .append("<itemsPrice>")
          .append(CurrencyUtil.displayFormatedAmountNoCurrency(total, "CAD"))
          .append("</itemsPrice>");
      request.append("<lineItems>");

      Iterator packageIterator = packages.iterator();
      while (packageIterator.hasNext()) {
        PackageDetail pack = (PackageDetail) packageIterator.next();
        request.append("<item>");
        request.append("<quantity>").append(pack.getShippingQuantity()).append("</quantity>");
        request
            .append("<weight>")
            .append(
                String.valueOf(
                    CurrencyUtil.getWeight(
                        pack.getShippingWeight(), store, Constants.KG_WEIGHT_UNIT)))
            .append("</weight>");
        request
            .append("<length>")
            .append(
                String.valueOf(
                    CurrencyUtil.getMeasure(
                        pack.getShippingLength(), store, Constants.CM_SIZE_UNIT)))
            .append("</length>");
        request
            .append("<width>")
            .append(
                String.valueOf(
                    CurrencyUtil.getMeasure(
                        pack.getShippingWidth(), store, Constants.CM_SIZE_UNIT)))
            .append("</width>");
        request
            .append("<height>")
            .append(
                String.valueOf(
                    CurrencyUtil.getMeasure(
                        pack.getShippingHeight(), store, Constants.CM_SIZE_UNIT)))
            .append("</height>");
        request.append("<description>").append(pack.getProductName()).append("</description>");
        request.append("<readyToShip/>");
        request.append("</item>");
      }

      Country c = null;
      Map countries =
          (Map)
              RefCache.getAllcountriesmap(LanguageUtil.getLanguageNumberCode(locale.getLanguage()));
      c = (Country) countries.get(store.getCountry());

      request.append("</lineItems>");
      request.append("<city>").append(customer.getCustomerCity()).append("</city>");

      request.append("<provOrState>").append(customer.getShippingSate()).append("</provOrState>");
      Map cs =
          (Map)
              RefCache.getAllcountriesmap(LanguageUtil.getLanguageNumberCode(locale.getLanguage()));
      Country customerCountry = (Country) cs.get(customer.getCustomerCountryId());
      request.append("<country>").append(customerCountry.getCountryName()).append("</country>");
      request
          .append("<postalCode>")
          .append(
              com.salesmanager.core.util.ShippingUtil.trimPostalCode(
                  customer.getCustomerPostalCode()))
          .append("</postalCode>");
      request.append("</ratesAndServicesRequest>");
      request.append("</eparcel>");

      /**
       * <?xml version="1.0" ?> <eparcel>
       * <!--********************************-->
       * <!-- Prefered language
       * for the -->
       * <!-- response (FR/EN) (optional) -->
       * <!--********************************-->
       * <language>en</language>
       *
       * <p><ratesAndServicesRequest>
       * <!--**********************************-->
       * <!-- Merchant
       * Identification assigned -->
       * <!-- by Canada Post -->
       * <!-- -->
       * <!--
       * Note: Use 'CPC_DEMO_HTML' or ask -->
       * <!-- our Help Desk to change
       * your -->
       * <!-- profile if you want HTML to be -->
       * <!-- returned to
       * you -->
       * <!--**********************************-->
       * <merchantCPCID> CPC_DEMO_XML </merchantCPCID>
       * <!--*********************************-->
       * <!--Origin Postal Code
       * -->
       * <!--This parameter is optional -->
       * <!--*********************************-->
       * <fromPostalCode>m1p1c0</fromPostalCode>
       * <!--**********************************-->
       * <!-- Turn Around Time
       * (hours) -->
       * <!-- This parameter is optional -->
       * <!--**********************************-->
       * <turnAroundTime> 24 </turnAroundTime>
       * <!--**********************************-->
       * <!-- Total amount in $
       * of the items -->
       * <!-- for insurance calculation -->
       * <!-- This
       * parameter is optional -->
       * <!--**********************************-->
       * <itemsPrice>0.00</itemsPrice>
       * <!--**********************************-->
       * <!-- List of items in
       * the shopping -->
       * <!-- cart -->
       * <!-- Each item is defined by : -->
       * <!-- - quantity (mandatory) -->
       * <!-- - size (mandatory) -->
       * <!--
       * - weight (mandatory) -->
       * <!-- - description (mandatory) -->
       * <!--
       * - ready to ship (optional) -->
       * <!--**********************************-->
       * <lineItems> <item> <quantity> 1 </quantity> <weight> 1.491 </weight> <length> 1 </length>
       * <width> 1 </width> <height> 1 </height> <description> KAO Diskettes </description> </item>
       *
       * <p><item> <quantity> 1 </quantity> <weight> 1.5 </weight> <length> 20 </length> <width> 30
       * </width> <height> 20 </height> <description> My Ready To Ship Item</description>
       * <!--**********************************************-->
       * <!-- By
       * adding the 'readyToShip' tag, Sell Online -->
       * <!-- will not pack
       * this item in the boxes -->
       * <!-- defined in the merchant profile.
       * -->
       * <!-- Instead, this item will be shipped in its -->
       * <!--
       * original box: 1.5 kg and 20x30x20 cm -->
       * <!--**********************************************-->
       * <readyToShip/> </item> </lineItems>
       * <!--********************************-->
       * <!-- City where the
       * parcel will be -->
       * <!-- shipped to -->
       * <!--********************************-->
       * <city> </city>
       * <!--********************************-->
       * <!-- Province (Canada) or
       * State (US)-->
       * <!-- where the parcel will be -->
       * <!-- shipped to
       * -->
       * <!--********************************-->
       * <provOrState> Wisconsin </provOrState>
       * <!--********************************-->
       * <!-- Country or ISO
       * Country code -->
       * <!-- where the parcel will be -->
       * <!-- shipped
       * to -->
       * <!--********************************-->
       * <country> CANADA </country>
       * <!--********************************-->
       * <!-- Postal Code (or ZIP)
       * where the -->
       * <!-- parcel will be shipped to -->
       * <!--********************************-->
       * <postalCode> H3K1E5</postalCode> </ratesAndServicesRequest> </eparcel>
       */
      log.debug("canadapost request " + request.toString());

      HttpClient client = new HttpClient();

      StringBuilder u =
          new StringBuilder().append(protocol).append("://").append(host).append(":").append(port);
      if (!StringUtils.isBlank(url)) {
        u.append(url);
      }

      log.debug("Canadapost URL " + u.toString());

      httppost = new PostMethod(u.toString());
      RequestEntity entity = new StringRequestEntity(request.toString(), "text/plain", "UTF-8");
      httppost.setRequestEntity(entity);

      int result = client.executeMethod(httppost);

      if (result != 200) {
        log.error(
            "Communication Error with canadapost " + protocol + "://" + host + ":" + port + url);
        throw new Exception(
            "Communication Error with canadapost " + protocol + "://" + host + ":" + port + url);
      }
      String stringresult = httppost.getResponseBodyAsString();
      log.debug("canadapost response " + stringresult);

      canadaPost = new CanadaPostParsedElements();
      Digester digester = new Digester();
      digester.push(canadaPost);

      digester.addCallMethod("eparcel/ratesAndServicesResponse/statusCode", "setStatusCode", 0);
      digester.addCallMethod(
          "eparcel/ratesAndServicesResponse/statusMessage", "setStatusMessage", 0);
      digester.addObjectCreate(
          "eparcel/ratesAndServicesResponse/product",
          com.salesmanager.core.entity.shipping.ShippingOption.class);
      digester.addSetProperties("eparcel/ratesAndServicesResponse/product", "sequence", "optionId");
      digester.addCallMethod(
          "eparcel/ratesAndServicesResponse/product/shippingDate", "setShippingDate", 0);
      digester.addCallMethod(
          "eparcel/ratesAndServicesResponse/product/deliveryDate", "setDeliveryDate", 0);
      digester.addCallMethod("eparcel/ratesAndServicesResponse/product/name", "setOptionName", 0);
      digester.addCallMethod(
          "eparcel/ratesAndServicesResponse/product/rate", "setOptionPriceText", 0);
      digester.addSetNext("eparcel/ratesAndServicesResponse/product", "addOption");

      /**
       * response
       *
       * <p><?xml version="1.0" ?> <!DOCTYPE eparcel (View Source for full doctype...)> - <eparcel>
       * - <ratesAndServicesResponse> <statusCode>1</statusCode> <statusMessage>OK</statusMessage>
       * <requestID>1769506</requestID> <handling>0.0</handling> <language>0</language> - <product
       * id="1040" sequence="1"> <name>Priority Courier</name> <rate>38.44</rate>
       * <shippingDate>2008-12-22</shippingDate> <deliveryDate>2008-12-23</deliveryDate>
       * <deliveryDayOfWeek>3</deliveryDayOfWeek> <nextDayAM>true</nextDayAM>
       * <packingID>P_0</packingID> </product> - <product id="1020" sequence="2">
       * <name>Expedited</name> <rate>16.08</rate> <shippingDate>2008-12-22</shippingDate>
       * <deliveryDate>2008-12-23</deliveryDate> <deliveryDayOfWeek>3</deliveryDayOfWeek>
       * <nextDayAM>false</nextDayAM> <packingID>P_0</packingID> </product> - <product id="1010"
       * sequence="3"> <name>Regular</name> <rate>16.08</rate>
       * <shippingDate>2008-12-22</shippingDate> <deliveryDate>2008-12-29</deliveryDate>
       * <deliveryDayOfWeek>2</deliveryDayOfWeek> <nextDayAM>false</nextDayAM>
       * <packingID>P_0</packingID> </product> - <packing> <packingID>P_0</packingID> - <box>
       * <name>Small Box</name> <weight>1.691</weight> <expediterWeight>1.691</expediterWeight>
       * <length>25.0</length> <width>17.0</width> <height>16.0</height> - <packedItem>
       * <quantity>1</quantity> <description>KAO Diskettes</description> </packedItem> </box> -
       * <box> <name>My Ready To Ship Item</name> <weight>2.0</weight>
       * <expediterWeight>1.5</expediterWeight> <length>30.0</length> <width>20.0</width>
       * <height>20.0</height> - <packedItem> <quantity>1</quantity> <description>My Ready To Ship
       * Item</description> </packedItem> </box> </packing> - <shippingOptions>
       * <insurance>No</insurance> <deliveryConfirmation>Yes</deliveryConfirmation>
       * <signature>No</signature> </shippingOptions> <comment /> </ratesAndServicesResponse>
       * </eparcel> -
       * <!-- END_OF_EPARCEL -->
       */
      Reader reader = new StringReader(stringresult);

      digester.parse(reader);

    } catch (Exception e) {
      log.error(e);
    } finally {
      if (httppost != null) {
        httppost.releaseConnection();
      }
    }

    if (canadaPost == null || canadaPost.getStatusCode() == null) {
      return null;
    }

    if (canadaPost.getStatusCode().equals("-6") || canadaPost.getStatusCode().equals("-7")) {
      LogMerchantUtil.log(
          store.getMerchantId(),
          "Can't process CanadaPost statusCode="
              + canadaPost.getStatusCode()
              + " message= "
              + canadaPost.getStatusMessage());
    }

    if (!canadaPost.getStatusCode().equals("1")) {
      log.error(
          "An error occured with canadapost request (code-> "
              + canadaPost.getStatusCode()
              + " message-> "
              + canadaPost.getStatusMessage()
              + ")");
      return null;
    }

    String carrier = getShippingMethodDescription(locale);
    // cost is in CAD, need to do conversion

    boolean requiresCurrencyConversion = false;
    String storeCurrency = store.getCurrency();
    if (!storeCurrency.equals(Constants.CURRENCY_CODE_CAD)) {
      requiresCurrencyConversion = true;
    }

    /** Details on whit RT quote information to display * */
    MerchantConfiguration rtdetails =
        config.getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_DISPLAY_REALTIME_QUOTES);
    int displayQuoteDeliveryTime = ShippingConstants.NO_DISPLAY_RT_QUOTE_TIME;
    if (rtdetails != null) {

      if (!StringUtils.isBlank(rtdetails.getConfigurationValue1())) { // display
        // or
        // not
        // quotes
        try {
          displayQuoteDeliveryTime = Integer.parseInt(rtdetails.getConfigurationValue1());

        } catch (Exception e) {
          log.error(
              "Display quote is not an integer value [" + rtdetails.getConfigurationValue1() + "]");
        }
      }
    }
    /**/

    List options = canadaPost.getOptions();
    if (options != null) {
      Iterator i = options.iterator();
      while (i.hasNext()) {
        ShippingOption option = (ShippingOption) i.next();
        option.setCurrency(store.getCurrency());
        StringBuffer description = new StringBuffer();
        description.append(option.getOptionName());
        if (displayQuoteDeliveryTime == ShippingConstants.DISPLAY_RT_QUOTE_TIME) {
          description.append(" (").append(option.getDeliveryDate()).append(")");
        }
        option.setDescription(description.toString());
        if (requiresCurrencyConversion) {
          option.setOptionPrice(
              CurrencyUtil.convertToCurrency(
                  option.getOptionPrice(), Constants.CURRENCY_CODE_CAD, store.getCurrency()));
        }
        // System.out.println(option.getOptionPrice().toString());

      }
    }

    return options;
  }
  public String execute(HttpServletRequest request) throws Exception {

    Customer customer = null;

    if (!validateCustomerLogon(request)) {

      LabelUtil l = LabelUtil.getInstance();
      Locale locale = LocaleUtil.getLocale(request);
      l.setLocale(locale);
      MessageUtil.addErrorMessage(request, l.getText(locale, "login.invalid"));
      return "redirect:/home.html";
    }
    try {

      CustomerLogonModule logon =
          (CustomerLogonModule) com.salesmanager.core.util.SpringUtil.getBean("customerLogon");

      // get merchantId
      int merchantId = 1;
      HttpSession session = request.getSession();
      MerchantStore store = (MerchantStore) session.getAttribute("STORE");
      if (store != null) {
        merchantId = store.getMerchantId();
      }

      customer = logon.logon(request, merchantId);

      if (customer == null) {

        MessageUtil.addErrorMessage(request, super.getText(request, "login.invalid"));
        return "redirect:/home.html";
      }

      Locale locale = LocaleUtil.getLocale(request);
      customer.setLocale(locale);

      // get CustomerInfo
      CustomerService cservice =
          (CustomerService) ServiceFactory.getService(ServiceFactory.CustomerService);
      CustomerInfo customerInfo = cservice.findCustomerInfoById(customer.getCustomerId());

      if (customerInfo == null) {
        customerInfo = new CustomerInfo();
        customerInfo.setCustomerInfoId(customer.getCustomerId());
      }

      Integer login = customerInfo.getCustomerInfoNumberOfLogon();
      login = login + 1;
      customerInfo.setCustomerInfoNumberOfLogon(login);
      cservice.saveOrUpdateCustomerInfo(customerInfo);

      SessionUtil.setCustomer(customer, request);
      request.setAttribute("CUSTOMER", customer);

      return "redirect:/profile/profile.html";

    } catch (ServiceException e) {

      MessageUtil.addErrorMessage(request, super.getText(request, "login.invalid"));
      return "redirect:/home.html";

    } catch (Exception ex) {
      log.error(ex);
      throw ex;
    }
  }