@RequestMapping(value = "/registration.html", method = RequestMethod.GET)
  public String displayRegistration(
      final Model model, final HttpServletRequest request, final HttpServletResponse response)
      throws Exception {

    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);

    model.addAttribute(
        "recapatcha_public_key", coreConfiguration.getProperty(Constants.RECAPATCHA_PUBLIC_KEY));

    SecuredShopPersistableCustomer customer = new SecuredShopPersistableCustomer();
    AnonymousCustomer anonymousCustomer =
        (AnonymousCustomer) request.getAttribute(Constants.ANONYMOUS_CUSTOMER);
    if (anonymousCustomer != null) {
      customer.setBilling(anonymousCustomer.getBilling());
    }

    model.addAttribute("customer", customer);

    /** template * */
    StringBuilder template =
        new StringBuilder()
            .append(ControllerConstants.Tiles.Customer.register)
            .append(".")
            .append(store.getStoreTemplate());

    return template.toString();
  }
예제 #2
0
  /**
   * Get the measure according to the appropriate measure base. If the measure configured in store
   * is IN and it needs CM or vise versa then the appropriate calculation is done
   *
   * @param weight
   * @param store
   * @param base
   * @return
   */
  public static double getMeasure(double measure, MerchantStore store, String base) {

    if (base.equals(MeasureUnit.IN.name())) {
      if (store.getSeizeunitcode().equals(MeasureUnit.IN.name())) {
        return new BigDecimal(String.valueOf(measure))
            .setScale(2, BigDecimal.ROUND_HALF_UP)
            .doubleValue();
      } else { // centimeter (inch to centimeter)
        double measureConstant = 2.54;

        double answer = measure * measureConstant;
        BigDecimal w = new BigDecimal(answer);
        return w.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
      }
    } else { // need CM
      if (store.getSeizeunitcode().equals(MeasureUnit.CM.name())) {
        return new BigDecimal(String.valueOf(measure)).setScale(2).doubleValue();
      } else { // in (centimeter to inch)
        double measureConstant = 0.39;

        double answer = measure * measureConstant;
        BigDecimal w = new BigDecimal(answer);
        return w.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
      }
    }
  }
  @PreAuthorize("hasRole('STORE')")
  @RequestMapping(value = "/admin/store/saveTemplate.html", method = RequestMethod.POST)
  public String saveTemplate(
      @ModelAttribute(value = "store") final MerchantStore store,
      BindingResult result,
      Model model,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    setMenu(model, request);

    MerchantStore sessionstore = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE);

    sessionstore.setStoreTemplate(store.getStoreTemplate());

    merchantStoreService.saveOrUpdate(sessionstore);

    request.setAttribute(Constants.ADMIN_STORE, sessionstore);

    // display templates
    model.addAttribute("templates", templates);

    model.addAttribute("success", "success");
    model.addAttribute("store", sessionstore);

    return "admin-store-branding";
  }
  @PreAuthorize("hasRole('STORE')")
  @RequestMapping(
      value = "/admin/store/removeImage.html",
      method = RequestMethod.POST,
      produces = "application/json")
  public @ResponseBody String removeImage(
      HttpServletRequest request, HttpServletResponse response, Locale locale) {

    MerchantStore store = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE);

    AjaxResponse resp = new AjaxResponse();

    try {

      contentService.removeFile(store.getCode(), FileContentType.LOGO, store.getStoreLogo());

      store.setStoreLogo(null);
      merchantStoreService.update(store);

    } catch (Exception e) {
      LOGGER.error("Error while deleting product", e);
      resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
      resp.setErrorMessage(e);
    }

    String returnString = resp.toJSONString();

    return returnString;
  }
예제 #5
0
  /**
   * Get the measure according to the appropriate measure base. If the measure configured in store
   * is LB and it needs KG then the appropriate calculation is done
   *
   * @param weight
   * @param store
   * @param base
   * @return
   */
  public static double getWeight(double weight, MerchantStore store, String base) {

    double weightConstant = 2.2;
    if (base.equals(MeasureUnit.LB.name())) {
      if (store.getWeightunitcode().equals(MeasureUnit.LB.name())) {
        return new BigDecimal(String.valueOf(weight))
            .setScale(2, BigDecimal.ROUND_HALF_UP)
            .doubleValue();
      } else { // pound = kilogram
        double answer = weight * weightConstant;
        BigDecimal w = new BigDecimal(answer);
        return w.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
      }
    } else { // need KG
      if (store.getWeightunitcode().equals(MeasureUnit.KG.name())) {
        return new BigDecimal(String.valueOf(weight))
            .setScale(2, BigDecimal.ROUND_HALF_UP)
            .doubleValue();
      } else {

        double answer = weight / weightConstant;
        BigDecimal w = new BigDecimal(answer);
        return w.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
      }
    }
  }
  /**
   * Removes a static file from the CMS
   *
   * @param request
   * @param response
   * @param locale
   * @return
   */
  @PreAuthorize("hasRole('CONTENT')")
  @RequestMapping(
      value = "/admin/content/static/removeFile.html",
      method = RequestMethod.POST,
      produces = "application/json")
  public @ResponseBody String removeFile(
      HttpServletRequest request, HttpServletResponse response, Locale locale) {
    String fileName = request.getParameter("name");

    MerchantStore store = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE);

    AjaxResponse resp = new AjaxResponse();

    try {

      contentService.removeFile(store.getCode(), FileContentType.STATIC_FILE, fileName);

      resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED);

    } catch (Exception e) {
      LOGGER.error("Error while deleting product", e);
      resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
      resp.setErrorMessage(e);
    }

    String returnString = resp.toJSONString();

    return returnString;
  }
예제 #7
0
  @Override
  public Address getAddress(
      Long userId, final MerchantStore merchantStore, boolean isBillingAddress) throws Exception {
    LOG.info("Fetching customer for id {} ", userId);
    Address address = null;
    final Customer customerModel = customerService.getById(userId);

    if (customerModel == null) {
      LOG.error("Customer with ID {} does not exists..", userId);
      throw new CustomerNotFoundException("customer with given id does not exists");
    }

    if (isBillingAddress) {
      LOG.info("getting billing address..");
      CustomerBillingAddressPopulator billingAddressPopulator =
          new CustomerBillingAddressPopulator();
      address =
          billingAddressPopulator.populate(
              customerModel, merchantStore, merchantStore.getDefaultLanguage());
      address.setBillingAddress(true);
      return address;
    }

    LOG.info("getting Delivery address..");
    CustomerDeliveryAddressPopulator deliveryAddressPopulator =
        new CustomerDeliveryAddressPopulator();
    return deliveryAddressPopulator.populate(
        customerModel, merchantStore, merchantStore.getDefaultLanguage());
  }
예제 #8
0
  @Override
  public void updateAddress(
      Long userId, MerchantStore merchantStore, Address address, final Language language)
      throws Exception {

    Customer customerModel = customerService.getById(userId);
    Map<String, Country> countriesMap = countryService.getCountriesMap(language);
    Country country = countriesMap.get(address.getCountry());

    if (customerModel == null) {
      LOG.error("Customer with ID {} does not exists..", userId);
      throw new CustomerNotFoundException("customer with given id does not exists");
    }
    if (address.isBillingAddress()) {
      LOG.info("updating customer billing address..");
      PersistableCustomerBillingAddressPopulator billingAddressPopulator =
          new PersistableCustomerBillingAddressPopulator();
      customerModel =
          billingAddressPopulator.populate(
              address, customerModel, merchantStore, merchantStore.getDefaultLanguage());
      customerModel.getBilling().setCountry(country);
      if (StringUtils.isNotBlank(address.getZone())) {
        Zone zone = zoneService.getByCode(address.getZone());
        if (zone == null) {
          throw new ConversionException("Unsuported zone code " + address.getZone());
        }
        customerModel.getBilling().setZone(zone);
        customerModel.getBilling().setState(null);

      } else {
        customerModel.getBilling().setZone(null);
      }

    } else {
      LOG.info("updating customer shipping address..");
      PersistableCustomerShippingAddressPopulator shippingAddressPopulator =
          new PersistableCustomerShippingAddressPopulator();
      customerModel =
          shippingAddressPopulator.populate(
              address, customerModel, merchantStore, merchantStore.getDefaultLanguage());
      customerModel.getDelivery().setCountry(country);
      if (StringUtils.isNotBlank(address.getZone())) {
        Zone zone = zoneService.getByCode(address.getZone());
        if (zone == null) {
          throw new ConversionException("Unsuported zone code " + address.getZone());
        }

        customerModel.getDelivery().setZone(zone);
        customerModel.getDelivery().setState(null);

      } else {
        customerModel.getDelivery().setZone(null);
      }
    }

    // same update address with customer model
    this.customerService.saveOrUpdate(customerModel);
  }
  public int doStartTag() throws JspException {
    try {

      HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

      MerchantStore merchantStore = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE);

      HttpSession session = request.getSession();

      StringBuilder imagePath = new StringBuilder();

      // TODO domain from merchant, else from global config, else from property (localhost)

      // example -> /static/1/PRODUCT/120/product1.jpg

      // @SuppressWarnings("unchecked")
      // Map<String,String> configurations = (Map<String,
      // String>)session.getAttribute("STORECONFIGURATION");
      // String scheme = (String)configurations.get("scheme");

      // if(StringUtils.isBlank(scheme)) {
      //	scheme = "http";
      // }

      @SuppressWarnings("unchecked")
      Map<String, String> configurations =
          (Map<String, String>) session.getAttribute(Constants.STORE_CONFIGURATION);
      String scheme = Constants.HTTP_SCHEME;
      if (configurations != null) {
        scheme = (String) configurations.get("scheme");
      }

      imagePath
          .append(scheme)
          .append("://")
          .append(merchantStore.getDomainName())
          .append("/")
          .append(request.getContextPath());

      imagePath

          // .append(scheme).append("://").append(merchantStore.getDomainName())
          .append(Constants.STATIC_URI)
          .append("/")
          .append(
              ImageFilePathUtils.buildProductImageFilePath(
                  merchantStore, product, this.getImageName()))
          .toString();

      pageContext.getOut().print(imagePath.toString());

    } catch (Exception ex) {
      LOGGER.error("Error while getting content url", ex);
    }
    return SKIP_BODY;
  }
  public int doStartTagInternal() throws JspException {
    try {

      if (filePathUtils == null) {
        WebApplicationContext wac = getRequestContext().getWebApplicationContext();
        AutowireCapableBeanFactory factory = wac.getAutowireCapableBeanFactory();
        factory.autowireBean(this);
      }

      HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

      MerchantStore merchantStore = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE);

      HttpSession session = request.getSession();

      StringBuilder filePath = new StringBuilder();

      // TODO domain from merchant, else from global config, else from property (localhost)

      // example -> "/files/{storeCode}/{fileName}.{extension}"

      @SuppressWarnings("unchecked")
      Map<String, String> configurations =
          (Map<String, String>) session.getAttribute(Constants.STORE_CONFIGURATION);
      String scheme = Constants.HTTP_SCHEME;
      if (configurations != null) {
        scheme = (String) configurations.get("scheme");
      }

      filePath
          .append(scheme)
          .append("://")
          .append(merchantStore.getDomainName())
          // .append("/")
          .append(request.getContextPath());

      filePath
          .append(filePathUtils.buildAdminDownloadProductFilePath(merchantStore, digitalProduct))
          .toString();

      pageContext.getOut().print(filePath.toString());

    } catch (Exception ex) {
      LOGGER.error("Error while getting content url", ex);
    }
    return SKIP_BODY;
  }
예제 #11
0
  /**
   * Method to check if given user exists for given username under given store. System treat
   * username as unique for a given store, customer is not allowed to use same username twice for a
   * given store, however it can be used for different stores.
   *
   * @param userName Customer slected userName
   * @param store store for which customer want to register
   * @return boolean flag indicating if user exists for given store or not
   * @throws Exception
   */
  @Override
  public boolean checkIfUserExists(final String userName, final MerchantStore store)
      throws Exception {
    if (StringUtils.isNotBlank(userName) && store != null) {
      Customer customer = customerService.getByNick(userName, store.getId());
      if (customer != null) {
        LOG.info(
            "Customer with userName {} already exists for store {} ",
            userName,
            store.getStorename());
        return true;
      }

      LOG.info("No customer found with userName {} for store {} ", userName, store.getStorename());
      return false;
    }
    LOG.info("Either userName is empty or we have not found any value for store");
    return false;
  }
예제 #12
0
  @RequestMapping("/shop/store/contactus.html")
  public String displayContact(
      Model model, HttpServletRequest request, HttpServletResponse response, Locale locale)
      throws Exception {

    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);

    Language language = (Language) request.getAttribute("LANGUAGE");

    ContactForm contact = new ContactForm();
    model.addAttribute("contact", contact);

    model.addAttribute(
        "recapatcha_public_key", coreConfiguration.getProperty(Constants.RECAPATCHA_PUBLIC_KEY));

    Content content = contentService.getByCode(Constants.CONTENT_CONTACT_US, store, language);
    ContentDescription contentDescription = null;
    if (content != null && content.isVisible()) {
      contentDescription = content.getDescription();
    }

    if (contentDescription != null) {

      // meta information
      PageInformation pageInformation = new PageInformation();
      pageInformation.setPageDescription(contentDescription.getMetatagDescription());
      pageInformation.setPageKeywords(contentDescription.getMetatagKeywords());
      pageInformation.setPageTitle(contentDescription.getTitle());
      pageInformation.setPageUrl(contentDescription.getName());

      request.setAttribute(Constants.REQUEST_PAGE_INFORMATION, pageInformation);

      model.addAttribute("content", contentDescription);
    }

    /** template * */
    StringBuilder template =
        new StringBuilder()
            .append(ControllerConstants.Tiles.Content.contactus)
            .append(".")
            .append(store.getStoreTemplate());
    return template.toString();
  }
예제 #13
0
  @Override
  public void saveCategory(MerchantStore store, PersistableCategory category) throws Exception {

    PersistableCategoryPopulator populator = new PersistableCategoryPopulator();
    populator.setCategoryService(categoryService);
    populator.setLanguageService(languageService);

    Category dbCategory =
        populator.populate(category, new Category(), store, store.getDefaultLanguage());

    this.saveCategory(store, dbCategory, null);
  }
예제 #14
0
  @RequestMapping(
      value = "/admin/options/remove.html",
      method = RequestMethod.POST,
      produces = "application/json")
  public @ResponseBody String deleteOption(
      HttpServletRequest request, HttpServletResponse response, Locale locale) {
    String sid = request.getParameter("optionId");

    MerchantStore store = (MerchantStore) request.getAttribute("MERCHANT_STORE");

    AjaxResponse resp = new AjaxResponse();

    try {

      Long id = Long.parseLong(sid);

      ProductOption entity = productOptionService.getById(store, id);

      if (entity == null
          || entity.getMerchantSore().getId().intValue() != store.getId().intValue()) {

        resp.setStatusMessage(messages.getMessage("message.unauthorized", locale));
        resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);

      } else {

        productOptionService.delete(entity);
        resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED);
      }

    } catch (Exception e) {
      LOGGER.error("Error while deleting option", e);
      resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
      resp.setErrorMessage(e);
    }

    String returnString = resp.toJSONString();

    return returnString;
  }
  /**
   * Method responsible for adding content files to underlying Infinispan cache. It will add given
   * content file(s) for given merchant store in the cache. Following steps will be performed in
   * order to add files
   *
   * <pre>
   * 1. Validate form data
   * 2. Get Merchant Store based on merchant Id.
   * 3. Call {@link InputContentFile} to add file(s).
   * </pre>
   *
   * @param contentImages
   * @param bindingResult
   * @param model
   * @param request
   * @return
   * @throws Exception
   */
  @PreAuthorize("hasRole('CONTENT')")
  @RequestMapping(value = "/admin/content/static/saveFiles.html", method = RequestMethod.POST)
  public String saveFiles(
      @ModelAttribute(value = "contentFiles") @Valid final ContentFiles contentFiles,
      final BindingResult bindingResult,
      final Model model,
      final HttpServletRequest request)
      throws Exception {

    this.setMenu(model, request);
    if (bindingResult.hasErrors()) {
      LOGGER.info("Found {} Validation errors", bindingResult.getErrorCount());
      return ControllerConstants.Tiles.ContentFiles.contentFiles;
    }
    final List<InputContentFile> contentFilesList = new ArrayList<InputContentFile>();
    final MerchantStore store = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE);
    if (CollectionUtils.isNotEmpty(contentFiles.getFile())) {
      LOGGER.info(
          "Saving {} content files for merchant {}", contentFiles.getFile().size(), store.getId());
      for (final MultipartFile multipartFile : contentFiles.getFile()) {
        if (!multipartFile.isEmpty()) {
          ByteArrayInputStream inputStream = new ByteArrayInputStream(multipartFile.getBytes());
          InputContentFile cmsContentImage = new InputContentFile();
          cmsContentImage.setFileName(multipartFile.getOriginalFilename());
          cmsContentImage.setFileContentType(FileContentType.STATIC_FILE);
          cmsContentImage.setFile(inputStream);
          contentFilesList.add(cmsContentImage);
        }
      }

      if (CollectionUtils.isNotEmpty(contentFilesList)) {
        contentService.addContentFiles(store.getCode(), contentFilesList);
      } else {
        // show error message on UI
      }
    }

    return ControllerConstants.Tiles.ContentFiles.contentFiles;
  }
예제 #16
0
  @PreAuthorize("hasRole('STORE')")
  @RequestMapping(value = "/admin/store/saveBranding.html", method = RequestMethod.POST)
  public String saveStoreBranding(
      @ModelAttribute(value = "contentImages") @Valid final ContentFiles contentImages,
      BindingResult result,
      Model model,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    setMenu(model, request);

    MerchantStore store = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE);

    if (contentImages.getFile() != null && contentImages.getFile().size() > 0) {

      String imageName = contentImages.getFile().get(0).getOriginalFilename();
      InputStream inputStream = contentImages.getFile().get(0).getInputStream();
      InputContentFile cmsContentImage = new InputContentFile();
      cmsContentImage.setFileName(imageName);
      cmsContentImage.setMimeType(contentImages.getFile().get(0).getContentType());
      cmsContentImage.setFile(inputStream);
      contentService.addLogo(store.getCode(), cmsContentImage);

      // Update store
      store.setStoreLogo(imageName);
      merchantStoreService.update(store);
      request.getSession().setAttribute(Constants.ADMIN_STORE, store);
    }

    // display templates
    model.addAttribute("templates", templates);

    model.addAttribute("success", "success");
    model.addAttribute("store", store);

    return "admin-store-branding";
  }
예제 #17
0
  @Override
  public List<IntegrationModule> getShippingMethods(MerchantStore store) throws ServiceException {

    List<IntegrationModule> modules =
        moduleConfigurationService.getIntegrationModules(SHIPPING_MODULES);
    List<IntegrationModule> returnModules = new ArrayList<IntegrationModule>();

    for (IntegrationModule module : modules) {
      if (module.getRegionsSet().contains(store.getCountry().getIsoCode())
          || module.getRegionsSet().contains("*")) {

        returnModules.add(module);
      }
    }

    return returnModules;
  }
예제 #18
0
  @Override
  public ShippingMetaData getShippingMetaData(MerchantStore store) throws ServiceException {

    ShippingMetaData metaData = new ShippingMetaData();

    // configured country
    List<Country> countries = getShipToCountryList(store, store.getDefaultLanguage());
    metaData.setShipToCountry(countries);

    // configured modules
    Map<String, IntegrationConfiguration> modules = getShippingModulesConfigured(store);
    List<String> moduleKeys = new ArrayList<String>();
    if (modules != null) {
      for (String key : modules.keySet()) {
        moduleKeys.add(key);
      }
    }
    metaData.setModules(moduleKeys);

    // pre processors
    List<ShippingQuotePrePostProcessModule> preProcessors = this.shippingModulePreProcessors;
    List<String> preProcessorKeys = new ArrayList<String>();
    if (preProcessors != null) {
      for (ShippingQuotePrePostProcessModule processor : preProcessors) {
        preProcessorKeys.add(processor.getModuleCode());
        if (SHIPPING_DISTANCE.equals(processor.getModuleCode())) {
          metaData.setUseDistanceModule(true);
        }
      }
    }
    metaData.setPreProcessors(preProcessorKeys);

    // post processors
    List<ShippingQuotePrePostProcessModule> postProcessors = this.shippingModulePostProcessors;
    List<String> postProcessorKeys = new ArrayList<String>();
    if (postProcessors != null) {
      for (ShippingQuotePrePostProcessModule processor : postProcessors) {
        postProcessorKeys.add(processor.getModuleCode());
      }
    }
    metaData.setPostProcessors(postProcessorKeys);

    return metaData;
  }
예제 #19
0
  @Override
  public List<Country> getShipToCountryList(MerchantStore store, Language language)
      throws ServiceException {

    ShippingConfiguration shippingConfiguration = getShippingConfiguration(store);
    ShippingType shippingType = ShippingType.INTERNATIONAL;
    List<String> supportedCountries = new ArrayList<String>();
    if (shippingConfiguration == null) {
      shippingConfiguration = new ShippingConfiguration();
    }

    if (shippingConfiguration.getShippingType() != null) {
      shippingType = shippingConfiguration.getShippingType();
    }

    if (shippingType.name().equals(ShippingType.NATIONAL.name())) {

      supportedCountries.add(store.getCountry().getIsoCode());

    } else {

      MerchantConfiguration configuration =
          merchantConfigurationService.getMerchantConfiguration(SUPPORTED_COUNTRIES, store);

      if (configuration != null) {

        String countries = configuration.getValue();
        if (!StringUtils.isBlank(countries)) {

          Object objRegions = JSONValue.parse(countries);
          JSONArray arrayRegions = (JSONArray) objRegions;
          @SuppressWarnings("rawtypes")
          Iterator i = arrayRegions.iterator();
          while (i.hasNext()) {
            supportedCountries.add((String) i.next());
          }
        }
      }
    }

    return countryService.getCountries(supportedCountries, language);
  }
  @Test
  public void testCreateManufacturerService() throws ServiceException {

    Language DEFAULT_LANGUAGE = languageService.getByCode("en");
    Language FRENCH = languageService.getByCode("fr");
    Currency currency = currencyService.getByCode("CAD");
    Country ca = super.countryService.getByCode("CA");

    // create a merchant
    MerchantStore store = new MerchantStore();
    store.setCountry(ca);
    store.setCurrency(currency);
    store.setDefaultLanguage(DEFAULT_LANGUAGE);
    store.setInBusinessSince(date);
    store.setStorename("store name");
    store.setStoreEmailAddress("*****@*****.**");
    merchantService.create(store);

    Manufacturer manufacturer = new Manufacturer();
    manufacturer.setMerchantSore(store);

    ManufacturerDescription fd = new ManufacturerDescription();
    fd.setLanguage(FRENCH);
    fd.setName("Sony french");
    fd.setManufacturer(manufacturer);

    ManufacturerDescription ed = new ManufacturerDescription();
    ed.setLanguage(DEFAULT_LANGUAGE);
    ed.setName("Sony english");
    ed.setManufacturer(manufacturer);

    Set descriptions = new HashSet();
    descriptions.add(fd);
    descriptions.add(ed);

    manufacturer.setDescriptions(descriptions);

    manufacturerService.create(manufacturer);

    manufacturerService.delete(manufacturer);
    // merchantService.delete(store);

  }
예제 #21
0
  private CustomerEntity customerEntityPoulator(
      final Customer customerModel, final MerchantStore merchantStore) {
    CustomerEntityPopulator customerPopulator = new CustomerEntityPopulator();
    try {
      CustomerEntity customerEntity =
          customerPopulator.populate(
              customerModel, merchantStore, merchantStore.getDefaultLanguage());
      if (customerEntity != null) {
        customerEntity.setId(customerModel.getId());
        LOG.info("Retunring populated instance of customer entity");
        return customerEntity;
      }
      LOG.warn(
          "Seems some issue with customerEntity populator..retunring null instance of customerEntity ");
      return null;

    } catch (ConversionException e) {
      LOG.error("Error while converting customer model to customer entity ", e);
    }
    return null;
  }
예제 #22
0
  @Test
  public void createStoreLogo() throws ServiceException, FileNotFoundException, IOException {

    MerchantStore store = merchantService.getByCode(MerchantStore.DEFAULT_STORE);
    final File file1 = new File("/Users/csamson777/Pictures/peavey.jpg");

    if (!file1.exists() || !file1.canRead()) {
      throw new ServiceException("Can't read" + file1.getAbsolutePath());
    }

    byte[] is = IOUtils.toByteArray(new FileInputStream(file1));
    ByteArrayInputStream inputStream = new ByteArrayInputStream(is);
    InputContentFile cmsContentImage = new InputContentFile();

    cmsContentImage.setFileName(file1.getName());
    cmsContentImage.setFile(inputStream);

    // logo as a content
    contentService.addLogo(store.getCode(), cmsContentImage);

    store.setStoreLogo(file1.getName());
    merchantService.update(store);

    // query the store
    store = merchantService.getByCode(MerchantStore.DEFAULT_STORE);

    // get the logo
    String logo = store.getStoreLogo();

    OutputContentFile image =
        contentService.getContentFile(store.getCode(), FileContentType.LOGO, logo);

    // print image
    OutputStream outputStream =
        new FileOutputStream("/Users/csamson777/Pictures/mexique" + image.getFileName());

    ByteArrayOutputStream baos = image.getFile();
    baos.writeTo(outputStream);

    // remove image
    contentService.removeFile(store.getCode(), FileContentType.LOGO, store.getStoreLogo());
  }
예제 #23
0
  private String displayOption(
      Long optionId,
      HttpServletRequest request,
      HttpServletResponse response,
      Model model,
      Locale locale)
      throws Exception {

    this.setMenu(model, request);
    MerchantStore store = (MerchantStore) request.getAttribute("MERCHANT_STORE");

    List<Language> languages = store.getLanguages();

    Set<ProductOptionDescription> descriptions = new HashSet<ProductOptionDescription>();

    ProductOption option = new ProductOption();

    if (optionId != null && optionId != 0) { // edit mode

      option = productOptionService.getById(store, optionId);

      if (option == null) {
        return "redirect:/admin/options/options.html";
      }

      Set<ProductOptionDescription> optionDescriptions = option.getDescriptions();

      for (Language l : languages) {

        ProductOptionDescription optionDescription = null;

        if (optionDescriptions != null) {

          for (ProductOptionDescription description : optionDescriptions) {

            String code = description.getLanguage().getCode();
            if (code.equals(l.getCode())) {
              optionDescription = description;
            }
          }
        }

        if (optionDescription == null) {
          optionDescription = new ProductOptionDescription();
          optionDescription.setLanguage(l);
        }

        descriptions.add(optionDescription);
      }

    } else {

      for (Language l : languages) {

        ProductOptionDescription desc = new ProductOptionDescription();
        desc.setLanguage(l);
        descriptions.add(desc);
      }
    }

    option.setDescriptions(descriptions);
    model.addAttribute("option", option);
    return "catalogue-options-details";
  }
  /**
   * Display files in a List grid
   *
   * @param request
   * @param response
   * @return
   */
  @SuppressWarnings({"unchecked"})
  @PreAuthorize("hasRole('CONTENT')")
  @RequestMapping(
      value = "/admin/content/static/page.html",
      method = RequestMethod.POST,
      produces = "application/json;charset=UTF-8")
  public @ResponseBody String pageStaticContent(
      HttpServletRequest request, HttpServletResponse response) {
    AjaxResponse resp = new AjaxResponse();

    try {

      MerchantStore store = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE);

      List<String> fileNames =
          contentService.getContentFilesNames(store.getCode(), FileContentType.STATIC_FILE);

      /*			Map<String,String> configurations = (Map<String, String>)request.getSession().getAttribute(Constants.STORE_CONFIGURATION);
      			String scheme = Constants.HTTP_SCHEME;
      			if(configurations!=null) {
      				scheme = (String)configurations.get("scheme");
      			}


      			StringBuilder storePath = new StringBuilder();
      			storePath.append(scheme).append("://")
      			.append(store.getDomainName())
      			.append(request.getContextPath());
      */

      if (fileNames != null) {

        for (String name : fileNames) {

          String mimeType = URLConnection.getFileNameMap().getContentTypeFor(name);

          // StringBuilder filePath = new StringBuilder();

          // filePath.append(storePath.toString()).append(filePathUtils.buildStaticFilePath(store,name));

          String filePath = imageUtils.buildStaticContentFilePath(store, name);

          // String filePath = filePathUtils.buildStaticFileAbsolutePath(store, name);

          @SuppressWarnings("rawtypes")
          Map entry = new HashMap();
          entry.put("name", name);
          entry.put("path", filePath.toString());
          entry.put("mimeType", mimeType);
          resp.addDataEntry(entry);
        }
      }

      resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS);

    } catch (Exception e) {
      LOGGER.error("Error while paging content images", e);
      resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
    }

    String returnString = resp.toJSONString();

    return returnString;
  }
  public List<OutputContentFile> getImages(MerchantStore store, FileContentType imageContentType)
      throws ServiceException {

    return getImages(store.getCode(), imageContentType);
  }
예제 #26
0
  @Override
  public ShippingQuote getShippingQuote(
      MerchantStore store, Delivery delivery, List<ShippingProduct> products, Language language)
      throws ServiceException {

    // ShippingConfiguration -> Global configuration of a given store
    // IntegrationConfiguration -> Configuration of a given module
    // IntegrationModule -> The concrete module as defined in integrationmodules.properties

    // delivery without postal code is accepted
    Validate.notNull(store, "MerchantStore must not be null");
    Validate.notNull(delivery, "Delivery must not be null");
    Validate.notEmpty(products, "products must not be empty");
    Validate.notNull(language, "Language must not be null");

    ShippingQuote shippingQuote = new ShippingQuote();
    ShippingQuoteModule shippingQuoteModule = null;

    try {

      if (StringUtils.isBlank(delivery.getPostalCode())) {
        shippingQuote.getWarnings().add("No postal code in delivery address");
        shippingQuote.setShippingReturnCode(ShippingQuote.NO_POSTAL_CODE);
      }

      // get configuration
      ShippingConfiguration shippingConfiguration = getShippingConfiguration(store);
      ShippingType shippingType = ShippingType.INTERNATIONAL;

      /** get shipping origin * */
      ShippingOrigin shippingOrigin = shippingOriginService.getByStore(store);
      if (shippingOrigin == null || !shippingOrigin.isActive()) {
        shippingOrigin = new ShippingOrigin();
        shippingOrigin.setAddress(store.getStoreaddress());
        shippingOrigin.setCity(store.getStorecity());
        shippingOrigin.setCountry(store.getCountry());
        shippingOrigin.setPostalCode(store.getStorepostalcode());
        shippingOrigin.setState(store.getStorestateprovince());
        shippingOrigin.setZone(store.getZone());
      }

      if (shippingConfiguration == null) {
        shippingConfiguration = new ShippingConfiguration();
      }

      if (shippingConfiguration.getShippingType() != null) {
        shippingType = shippingConfiguration.getShippingType();
      }

      // look if customer country code excluded
      Country shipCountry = delivery.getCountry();
      if (shipCountry == null) {
        throw new ServiceException("Delivery country is null");
      }

      // a ship to country is required
      Validate.notNull(shipCountry);
      Validate.notNull(store.getCountry());

      if (shippingType.name().equals(ShippingType.NATIONAL.name())) {
        // customer country must match store country
        if (!shipCountry.getIsoCode().equals(store.getCountry().getIsoCode())) {
          shippingQuote.setShippingReturnCode(
              ShippingQuote.NO_SHIPPING_TO_SELECTED_COUNTRY + " " + shipCountry.getIsoCode());
          return shippingQuote;
        }
      } else if (shippingType.name().equals(ShippingType.INTERNATIONAL.name())) {

        // customer shipping country code must be in accepted list
        List<String> supportedCountries = this.getSupportedCountries(store);
        if (!supportedCountries.contains(shipCountry.getIsoCode())) {
          shippingQuote.setShippingReturnCode(
              ShippingQuote.NO_SHIPPING_TO_SELECTED_COUNTRY + " " + shipCountry.getIsoCode());
          return shippingQuote;
        }
      }

      // must have a shipping module configured
      Map<String, IntegrationConfiguration> modules = this.getShippingModulesConfigured(store);
      if (modules == null) {
        shippingQuote.setShippingReturnCode(ShippingQuote.NO_SHIPPING_MODULE_CONFIGURED);
        return shippingQuote;
      }

      /** uses this module name * */
      String moduleName = null;
      IntegrationConfiguration configuration = null;
      for (String module : modules.keySet()) {
        moduleName = module;
        configuration = modules.get(module);
        // use the first active module
        if (configuration.isActive()) {
          shippingQuoteModule = this.shippingModules.get(module);
          if (shippingQuoteModule instanceof ShippingQuotePrePostProcessModule) {
            shippingQuoteModule = null;
            continue;
          } else {
            break;
          }
        }
      }

      if (shippingQuoteModule == null) {
        shippingQuote.setShippingReturnCode(ShippingQuote.NO_SHIPPING_MODULE_CONFIGURED);
        return shippingQuote;
      }

      /** merchant module configs * */
      List<IntegrationModule> shippingMethods = this.getShippingMethods(store);
      IntegrationModule shippingModule = null;
      for (IntegrationModule mod : shippingMethods) {
        if (mod.getCode().equals(moduleName)) {
          shippingModule = mod;
          break;
        }
      }

      /** general module configs * */
      if (shippingModule == null) {
        shippingQuote.setShippingReturnCode(ShippingQuote.NO_SHIPPING_MODULE_CONFIGURED);
        return shippingQuote;
      }

      // calculate order total
      BigDecimal orderTotal = calculateOrderTotal(products, store);
      List<PackageDetails> packages = this.getPackagesDetails(products, store);

      // free shipping ?
      if (shippingConfiguration.isFreeShippingEnabled()) {
        BigDecimal freeShippingAmount = shippingConfiguration.getOrderTotalFreeShipping();
        if (freeShippingAmount != null) {
          if (orderTotal.doubleValue() > freeShippingAmount.doubleValue()) {
            if (shippingConfiguration.getFreeShippingType() == ShippingType.NATIONAL) {
              if (store.getCountry().getIsoCode().equals(shipCountry.getIsoCode())) {
                shippingQuote.setFreeShipping(true);
                shippingQuote.setFreeShippingAmount(freeShippingAmount);
                return shippingQuote;
              }
            } else { // international all
              shippingQuote.setFreeShipping(true);
              shippingQuote.setFreeShippingAmount(freeShippingAmount);
              return shippingQuote;
            }
          }
        }
      }

      // handling fees
      BigDecimal handlingFees = shippingConfiguration.getHandlingFees();
      if (handlingFees != null) {
        shippingQuote.setHandlingFees(handlingFees);
      }

      // tax basis
      shippingQuote.setApplyTaxOnShipping(shippingConfiguration.isTaxOnShipping());

      Locale locale = languageService.toLocale(language);

      // invoke pre processors
      if (!CollectionUtils.isEmpty(shippingModulePreProcessors)) {
        for (ShippingQuotePrePostProcessModule preProcessor : shippingModulePreProcessors) {
          // System.out.println("Using pre-processor " + preProcessor.getModuleCode());
          preProcessor.prePostProcessShippingQuotes(
              shippingQuote,
              packages,
              orderTotal,
              delivery,
              shippingOrigin,
              store,
              configuration,
              shippingModule,
              shippingConfiguration,
              shippingMethods,
              locale);
          // TODO switch module if required
          if (shippingQuote.getCurrentShippingModule() != null
              && !shippingQuote
                  .getCurrentShippingModule()
                  .getCode()
                  .equals(shippingModule.getCode())) {
            shippingModule = shippingQuote.getCurrentShippingModule();
            moduleName = shippingModule.getCode();
            shippingQuoteModule = this.shippingModules.get(shippingModule.getCode());
            configuration = modules.get(shippingModule.getCode());
          }
        }
      }

      // invoke module
      List<ShippingOption> shippingOptions = null;

      try {
        shippingOptions =
            shippingQuoteModule.getShippingQuotes(
                shippingQuote,
                packages,
                orderTotal,
                delivery,
                shippingOrigin,
                store,
                configuration,
                shippingModule,
                shippingConfiguration,
                locale);
      } catch (Exception e) {
        LOGGER.error("Error while calculating shipping", e);
        merchantLogService.save(
            new MerchantLog(
                store, "Can't process " + shippingModule.getModule() + " -> " + e.getMessage()));
        shippingQuote.setQuoteError(e.getMessage());
        shippingQuote.setShippingReturnCode(ShippingQuote.ERROR);
        return shippingQuote;
      }

      if (shippingOptions == null && !StringUtils.isBlank(delivery.getPostalCode())) {
        shippingQuote.setShippingReturnCode(ShippingQuote.NO_SHIPPING_TO_SELECTED_COUNTRY);
      }

      shippingQuote.setShippingModuleCode(moduleName);

      // filter shipping options
      ShippingOptionPriceType shippingOptionPriceType =
          shippingConfiguration.getShippingOptionPriceType();
      ShippingOption selectedOption = null;

      if (shippingOptions != null) {

        for (ShippingOption option : shippingOptions) {
          if (selectedOption == null) {
            selectedOption = option;
          }
          // set price text
          String priceText = pricingService.getDisplayAmount(option.getOptionPrice(), store);
          option.setOptionPriceText(priceText);
          option.setShippingModuleCode(moduleName);

          if (StringUtils.isBlank(option.getOptionName())) {

            String countryName = delivery.getCountry().getName();
            if (countryName == null) {
              Map<String, Country> deliveryCountries = countryService.getCountriesMap(language);
              Country dCountry =
                  (Country) deliveryCountries.get(delivery.getCountry().getIsoCode());
              if (dCountry != null) {
                countryName = dCountry.getName();
              } else {
                countryName = delivery.getCountry().getIsoCode();
              }
            }
            option.setOptionName(countryName);
          }

          if (shippingOptionPriceType.name().equals(ShippingOptionPriceType.HIGHEST.name())) {

            if (option.getOptionPrice().longValue() > selectedOption.getOptionPrice().longValue()) {
              selectedOption = option;
            }
          }

          if (shippingOptionPriceType.name().equals(ShippingOptionPriceType.LEAST.name())) {

            if (option.getOptionPrice().longValue() < selectedOption.getOptionPrice().longValue()) {
              selectedOption = option;
            }
          }

          if (shippingOptionPriceType.name().equals(ShippingOptionPriceType.ALL.name())) {

            if (option.getOptionPrice().longValue() < selectedOption.getOptionPrice().longValue()) {
              selectedOption = option;
            }
          }
        }

        shippingQuote.setSelectedShippingOption(selectedOption);

        if (selectedOption != null
            && !shippingOptionPriceType.name().equals(ShippingOptionPriceType.ALL.name())) {
          shippingOptions = new ArrayList<ShippingOption>();
          shippingOptions.add(selectedOption);
        }
      }

      /** set final delivery address * */
      shippingQuote.setDeliveryAddress(delivery);

      shippingQuote.setShippingOptions(shippingOptions);

      /** post processors * */
      // invoke pre processors
      if (!CollectionUtils.isEmpty(shippingModulePostProcessors)) {
        for (ShippingQuotePrePostProcessModule postProcessor : shippingModulePostProcessors) {
          // get module info

          // get module configuration
          IntegrationConfiguration integrationConfiguration =
              modules.get(postProcessor.getModuleCode());

          IntegrationModule postProcessModule = null;
          for (IntegrationModule mod : shippingMethods) {
            if (mod.getCode().equals(postProcessor.getModuleCode())) {
              postProcessModule = mod;
              break;
            }
          }

          IntegrationModule module = postProcessModule;
          postProcessor.prePostProcessShippingQuotes(
              shippingQuote,
              packages,
              orderTotal,
              delivery,
              shippingOrigin,
              store,
              integrationConfiguration,
              module,
              shippingConfiguration,
              shippingMethods,
              locale);
        }
      }

    } catch (Exception e) {
      throw new ServiceException(e);
    }

    return shippingQuote;
  }
예제 #27
0
  @RequestMapping(
      value = {"/shop/store/{storeCode}/contact"},
      method = RequestMethod.POST)
  public @ResponseBody String sendEmail(
      @ModelAttribute(value = "contact") ContactForm contact,
      BindingResult bindingResult,
      HttpServletRequest request,
      HttpServletResponse response,
      Locale locale)
      throws Exception {

    AjaxResponse ajaxResponse = new AjaxResponse();

    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);

    try {

      if (StringUtils.isBlank(contact.getCaptchaResponseField())) {
        FieldError error =
            new FieldError(
                "captchaResponseField",
                "captchaResponseField",
                messages.getMessage("NotEmpty.contact.captchaResponseField", locale));
        bindingResult.addError(error);
        ajaxResponse.setErrorString(bindingResult.getAllErrors().get(0).getDefaultMessage());
        ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
        return ajaxResponse.toJSONString();
      }

      ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
      reCaptcha.setPublicKey(coreConfiguration.getProperty(Constants.RECAPATCHA_PUBLIC_KEY));
      reCaptcha.setPrivateKey(coreConfiguration.getProperty(Constants.RECAPATCHA_PRIVATE_KEY));

      if (StringUtils.isNotBlank(contact.getCaptchaChallengeField())
          && StringUtils.isNotBlank(contact.getCaptchaResponseField())) {
        ReCaptchaResponse reCaptchaResponse =
            reCaptcha.checkAnswer(
                request.getRemoteAddr(),
                contact.getCaptchaChallengeField(),
                contact.getCaptchaResponseField());
        if (!reCaptchaResponse.isValid()) {
          LOGGER.debug("Captcha response does not matched");
          FieldError error =
              new FieldError(
                  "captchaChallengeField",
                  "captchaChallengeField",
                  messages.getMessage("validaion.recaptcha.not.matched", locale));
          bindingResult.addError(error);
        }
      }

      if (bindingResult.hasErrors()) {
        LOGGER.debug(
            "found {} validation error while validating in customer registration ",
            bindingResult.getErrorCount());
        ajaxResponse.setErrorString(bindingResult.getAllErrors().get(0).getDefaultMessage());
        ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
        return ajaxResponse.toJSONString();
      }

      emailTemplatesUtils.sendContactEmail(
          contact,
          store,
          LocaleUtils.getLocale(store.getDefaultLanguage()),
          request.getContextPath());

      ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS);
    } catch (Exception e) {
      LOGGER.error("An error occured while trying to send an email", e);
      ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
    }

    return ajaxResponse.toJSONString();
  }
  @RequestMapping(value = "/register.html", method = RequestMethod.POST)
  public String registerCustomer(
      @Valid @ModelAttribute("customer") SecuredShopPersistableCustomer customer,
      BindingResult bindingResult,
      Model model,
      HttpServletRequest request,
      final Locale locale)
      throws Exception {
    MerchantStore merchantStore = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
    Language language = super.getLanguage(request);

    ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
    reCaptcha.setPublicKey(coreConfiguration.getProperty(Constants.RECAPATCHA_PUBLIC_KEY));
    reCaptcha.setPrivateKey(coreConfiguration.getProperty(Constants.RECAPATCHA_PRIVATE_KEY));

    String userName = null;
    String password = null;

    model.addAttribute(
        "recapatcha_public_key", coreConfiguration.getProperty(Constants.RECAPATCHA_PUBLIC_KEY));

    if (StringUtils.isNotBlank(customer.getRecaptcha_challenge_field())
        && StringUtils.isNotBlank(customer.getRecaptcha_response_field())) {
      ReCaptchaResponse reCaptchaResponse =
          reCaptcha.checkAnswer(
              request.getRemoteAddr(),
              customer.getRecaptcha_challenge_field(),
              customer.getRecaptcha_response_field());
      if (!reCaptchaResponse.isValid()) {
        LOGGER.debug("Captcha response does not matched");
        FieldError error =
            new FieldError(
                "recaptcha_challenge_field",
                "recaptcha_challenge_field",
                messages.getMessage("validaion.recaptcha.not.matched", locale));
        bindingResult.addError(error);
      }
    }

    if (StringUtils.isNotBlank(customer.getUserName())) {
      if (customerFacade.checkIfUserExists(customer.getUserName(), merchantStore)) {
        LOGGER.debug(
            "Customer with username {} already exists for this store ", customer.getUserName());
        FieldError error =
            new FieldError(
                "userName",
                "userName",
                messages.getMessage("registration.username.already.exists", locale));
        bindingResult.addError(error);
      }
      userName = customer.getUserName();
    }

    if (StringUtils.isNotBlank(customer.getPassword())
        && StringUtils.isNotBlank(customer.getCheckPassword())) {
      if (!customer.getPassword().equals(customer.getCheckPassword())) {
        FieldError error =
            new FieldError(
                "password",
                "password",
                messages.getMessage("message.password.checkpassword.identical", locale));
        bindingResult.addError(error);
      }
      password = customer.getPassword();
    }

    if (bindingResult.hasErrors()) {
      LOGGER.debug(
          "found {} validation error while validating in customer registration ",
          bindingResult.getErrorCount());
      StringBuilder template =
          new StringBuilder()
              .append(ControllerConstants.Tiles.Customer.register)
              .append(".")
              .append(merchantStore.getStoreTemplate());
      return template.toString();
    }

    @SuppressWarnings("unused")
    CustomerEntity customerData = null;
    try {
      customerData = customerFacade.registerCustomer(customer, merchantStore, language);
    } catch (CustomerRegistrationException cre) {
      LOGGER.error("Error while registering customer.. ", cre);
      ObjectError error =
          new ObjectError("registration", messages.getMessage("registration.failed", locale));
      bindingResult.addError(error);
      StringBuilder template =
          new StringBuilder()
              .append(ControllerConstants.Tiles.Customer.register)
              .append(".")
              .append(merchantStore.getStoreTemplate());
      return template.toString();
    } catch (Exception e) {
      LOGGER.error("Error while registering customer.. ", e);
      ObjectError error =
          new ObjectError("registration", messages.getMessage("registration.failed", locale));
      bindingResult.addError(error);
      StringBuilder template =
          new StringBuilder()
              .append(ControllerConstants.Tiles.Customer.register)
              .append(".")
              .append(merchantStore.getStoreTemplate());
      return template.toString();
    }

    /** Send registration email */
    emailTemplatesUtils.sendRegistrationEmail(
        customer, merchantStore, locale, request.getContextPath());

    /** Login user */
    try {

      // refresh customer
      Customer c = customerFacade.getCustomerByUserName(customer.getUserName(), merchantStore);
      // authenticate
      customerFacade.authenticate(c, userName, password);
      super.setSessionAttribute(Constants.CUSTOMER, c, request);

      return "redirect:/shop/customer/dashboard.html";

    } catch (Exception e) {
      LOGGER.error("Cannot authenticate user ", e);
      ObjectError error =
          new ObjectError("registration", messages.getMessage("registration.failed", locale));
      bindingResult.addError(error);
    }

    StringBuilder template =
        new StringBuilder()
            .append(ControllerConstants.Tiles.Customer.register)
            .append(".")
            .append(merchantStore.getStoreTemplate());
    return template.toString();
  }
예제 #29
0
  @RequestMapping(
      value = {"/shop/home.html", "/shop/", "/shop"},
      method = RequestMethod.GET)
  public String displayLanding(
      Model model, HttpServletRequest request, HttpServletResponse response, Locale locale)
      throws Exception {

    Language language = (Language) request.getAttribute(Constants.LANGUAGE);

    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);

    Content content = contentService.getByCode("LANDING_PAGE", store, language);

    /** Rebuild breadcrumb * */
    BreadcrumbItem item = new BreadcrumbItem();
    item.setItemType(BreadcrumbItemType.HOME);
    item.setLabel(messages.getMessage(Constants.HOME_MENU_KEY, locale));
    item.setUrl(Constants.HOME_URL);

    Breadcrumb breadCrumb = new Breadcrumb();
    breadCrumb.setLanguage(language);

    List<BreadcrumbItem> items = new ArrayList<BreadcrumbItem>();
    items.add(item);

    breadCrumb.setBreadCrumbs(items);
    request.getSession().setAttribute(Constants.BREADCRUMB, breadCrumb);
    request.setAttribute(Constants.BREADCRUMB, breadCrumb);
    /** * */
    if (content != null) {

      ContentDescription description = content.getDescription();

      model.addAttribute("page", description);

      PageInformation pageInformation = new PageInformation();
      pageInformation.setPageTitle(description.getName());
      pageInformation.setPageDescription(description.getMetatagDescription());
      pageInformation.setPageKeywords(description.getMetatagKeywords());

      request.setAttribute(Constants.REQUEST_PAGE_INFORMATION, pageInformation);
    }

    ReadableProductPopulator populator = new ReadableProductPopulator();
    populator.setPricingService(pricingService);

    // featured items
    List<ProductRelationship> relationships =
        productRelationshipService.getByType(
            store, ProductRelationshipType.FEATURED_ITEM, language);
    List<ReadableProduct> featuredItems = new ArrayList<ReadableProduct>();
    for (ProductRelationship relationship : relationships) {

      Product product = relationship.getRelatedProduct();
      ReadableProduct proxyProduct =
          populator.populate(product, new ReadableProduct(), store, language);

      featuredItems.add(proxyProduct);
    }

    model.addAttribute("featuredItems", featuredItems);

    /** template * */
    StringBuilder template =
        new StringBuilder().append("landing.").append(store.getStoreTemplate());

    return template.toString();
  }
예제 #30
0
 @Override
 public Customer getCustomerByUserName(String userName, MerchantStore store) throws Exception {
   return customerService.getByNick(userName, store.getId());
 }