Example #1
0
  /**
   * 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;
  }
@Service
public class CustomerService {

  private static Configuration config = PropertiesUtil.getConfiguration();

  @Autowired private ICustomerDao customerDao;

  @Autowired private ICustomerInfoDao customerInfoDao;

  @Transactional
  public Collection<Customer> getCustomersByCompanyName(int merchantId, String companyName)
      throws Exception {
    return customerDao.findByCompanyName(companyName, merchantId);
  }

  @Transactional
  public Collection<Customer> getCustomersHavingCompanies(int merchantId) throws Exception {
    return customerDao.findCustomersHavingCompany(merchantId);
  }

  @Transactional
  public Collection<String> getUniqueCustomerCompanyNameList(int merchantId) throws Exception {
    return customerDao.findUniqueCompanyName(merchantId);
  }

  /**
   * When a customer is logged in the product is added to the CUSTOMERS_BASKET table
   *
   * @param productid
   * @param quantity
   * @param price
   * @param merchantid
   */
  @Transactional
  public void addProductToSavedCart(CustomerBasket basket) throws Exception {

    // @todo, use saveall
    customerDao.saveShoppingCart(basket);
    List basketAttributes = basket.getCustomerBasketAttributes();
    if (basketAttributes != null) {
      Iterator i = basketAttributes.iterator();
      while (i.hasNext()) {
        CustomerBasketAttribute basketattribute = (CustomerBasketAttribute) i.next();
        customerDao.saveShoppingCartAttributes(basketattribute);
      }
    }
  }

  /**
   * Retreives a Customer entity based on the id
   *
   * @param customerId
   * @return
   * @throws Exception
   */
  @Transactional
  public Customer getCustomer(long customerId) throws Exception {
    return customerDao.findById(customerId);
  }

  /**
   * Retreives a list of customer for a given merchantid
   *
   * @param merchantId
   * @return
   * @throws Exception
   */
  @Transactional
  public Collection<Customer> getCustomerList(int merchantId) throws Exception {
    return customerDao.findByMerchantId(merchantId);
  }

  /**
   * Deletes all Customer created by a given merchantId
   *
   * @param merchantId
   * @throws Exception
   */
  @Transactional
  public void deleteAllCustomers(int merchantId) throws Exception {
    Collection customers = getCustomerList(merchantId);
    if (customers != null && customers.size() > 0) {
      Iterator i = customers.iterator();
      while (i.hasNext()) {
        Customer customer = (Customer) i.next();
        deleteCustomer(customer);
      }
    }
  }

  @Transactional
  public void deleteCustomer(Customer customer) throws Exception {
    CustomerInfo info = customerInfoDao.findById(customer.getCustomerId());
    if (info != null) {
      customerInfoDao.delete(info);
    }

    // customer basket

    // wishlist

    customerDao.delete(customer);
  }

  /**
   * Search customers using criteria
   *
   * @param criteria
   * @return
   * @throws Exception
   */
  @Transactional
  public SearchCustomerResponse searchCustomers(SearchCustomerCriteria criteria) throws Exception {
    return customerDao.findCustomers(criteria);
  }

  @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);
  }

  /**
   * 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
  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;
  }

  @Transactional
  public Customer findCustomerbyUserNameAndPassword(
      String userName, String password, int merchantId) throws Exception {
    return customerDao.findByUserNameAndPasswordByMerchantId(userName, password, merchantId);
  }

  @Transactional
  public Customer findCustomerByEmail(String email) {
    return customerDao.findCustomerbyEmail(email);
  }

  @Transactional
  public Customer findCustomerByUserName(String userName, int merchantId) {
    return customerDao.findCustomerbyUserName(userName, merchantId);
  }

  @Transactional
  public Date processLastLoggedInDate(long customerId) {
    Date lastLoggedInDate = null;
    if (customerId != 0) {
      CustomerInfo info = customerInfoDao.findById(customerId);
      if (info != null) {
        lastLoggedInDate = info.getCustomerInfoDateOfLastLogon();
      } else {
        // SET it as current date if it is customer's first login.
        lastLoggedInDate = new Date();
        info = new CustomerInfo();
        info.setCustomerInfoId(customerId);
        info.setCustomerInfoDateAccountCreated(new Date());
      }
      info.setCustomerInfoDateOfLastLogon(new Date());
      info.setCustomerInfoNumberOfLogon(
          new Integer(
              ((info.getCustomerInfoNumberOfLogon() != null)
                      ? info.getCustomerInfoNumberOfLogon()
                      : 0)
                  + 1));
      customerInfoDao.saveOrUpdate(info);
    }
    return lastLoggedInDate;
  }

  @Transactional
  public void saveOrUpdateCustomerInfo(CustomerInfo customerInfo) {
    customerInfoDao.saveOrUpdate(customerInfo);
  }

  @Transactional
  public CustomerInfo findCustomerInfoById(long id) {
    return customerInfoDao.findById(id);
  }
}
Example #3
0
  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());
      }
    }
  }