Search in sources :

Example 1 with Billing

use of com.salesmanager.core.model.common.Billing in project shopizer by shopizer-ecommerce.

the class ShoppingOrderController method displayCheckout.

@SuppressWarnings("unused")
@RequestMapping("/checkout.html")
public String displayCheckout(@CookieValue("cart") String cookie, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
    Language language = (Language) request.getAttribute("LANGUAGE");
    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
    Customer customer = (Customer) request.getSession().getAttribute(Constants.CUSTOMER);
    model.addAttribute("googleMapsKey", googleMapsKey);
    /**
     * Shopping cart
     *
     * ShoppingCart should be in the HttpSession
     * Otherwise the cart id is in the cookie
     * Otherwise the customer is in the session and a cart exist in the DB
     * Else -> Nothing to display
     */
    // check if an existing order exist
    ShopOrder order = null;
    order = super.getSessionAttribute(Constants.ORDER, request);
    // Get the cart from the DB
    String shoppingCartCode = (String) request.getSession().getAttribute(Constants.SHOPPING_CART);
    com.salesmanager.core.model.shoppingcart.ShoppingCart cart = null;
    if (StringUtils.isBlank(shoppingCartCode)) {
        if (cookie == null) {
            // session expired and cookie null, nothing to do
            return "redirect:/shop/cart/shoppingCart.html";
        }
        String[] merchantCookie = cookie.split("_");
        String merchantStoreCode = merchantCookie[0];
        if (!merchantStoreCode.equals(store.getCode())) {
            return "redirect:/shop/cart/shoppingCart.html";
        }
        shoppingCartCode = merchantCookie[1];
    }
    cart = shoppingCartFacade.getShoppingCartModel(shoppingCartCode, store);
    if (cart == null && customer != null) {
        cart = shoppingCartFacade.getShoppingCartModel(customer, store);
    }
    boolean allAvailables = true;
    boolean requiresShipping = false;
    boolean freeShoppingCart = true;
    // Filter items, delete unavailable
    Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> availables = new HashSet<ShoppingCartItem>();
    if (cart == null) {
        return "redirect:/shop/cart/shoppingCart.html";
    }
    // Take out items no more available
    Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> items = cart.getLineItems();
    for (com.salesmanager.core.model.shoppingcart.ShoppingCartItem item : items) {
        Long id = item.getProduct().getId();
        Product p = productService.getById(id);
        if (p.isAvailable()) {
            availables.add(item);
        } else {
            allAvailables = false;
        }
        FinalPrice finalPrice = pricingService.calculateProductPrice(p);
        if (finalPrice.getFinalPrice().longValue() > 0) {
            freeShoppingCart = false;
        }
        if (p.isProductShipeable()) {
            requiresShipping = true;
        }
    }
    cart.setLineItems(availables);
    if (!allAvailables) {
        shoppingCartFacade.saveOrUpdateShoppingCart(cart);
    }
    super.setSessionAttribute(Constants.SHOPPING_CART, cart.getShoppingCartCode(), request);
    if (shoppingCartCode == null && cart == null) {
        // error
        return "redirect:/shop/cart/shoppingCart.html";
    }
    if (customer != null) {
        if (cart.getCustomerId() != customer.getId().longValue()) {
            return "redirect:/shop/shoppingCart.html";
        }
    } else {
        customer = orderFacade.initEmptyCustomer(store);
        AnonymousCustomer anonymousCustomer = (AnonymousCustomer) request.getAttribute(Constants.ANONYMOUS_CUSTOMER);
        if (anonymousCustomer != null && anonymousCustomer.getBilling() != null) {
            Billing billing = customer.getBilling();
            billing.setCity(anonymousCustomer.getBilling().getCity());
            Map<String, Country> countriesMap = countryService.getCountriesMap(language);
            Country anonymousCountry = countriesMap.get(anonymousCustomer.getBilling().getCountry());
            if (anonymousCountry != null) {
                billing.setCountry(anonymousCountry);
            }
            Map<String, Zone> zonesMap = zoneService.getZones(language);
            Zone anonymousZone = zonesMap.get(anonymousCustomer.getBilling().getZone());
            if (anonymousZone != null) {
                billing.setZone(anonymousZone);
            }
            if (anonymousCustomer.getBilling().getPostalCode() != null) {
                billing.setPostalCode(anonymousCustomer.getBilling().getPostalCode());
            }
            customer.setBilling(billing);
        }
    }
    if (CollectionUtils.isEmpty(items)) {
        return "redirect:/shop/shoppingCart.html";
    }
    if (order == null) {
        // TODO
        order = orderFacade.initializeOrder(store, customer, cart, language);
    }
    /**
     * hook for displaying or not delivery address configuration
     */
    ShippingMetaData shippingMetaData = shippingService.getShippingMetaData(store);
    model.addAttribute("shippingMetaData", shippingMetaData);
    /**
     * shipping *
     */
    ShippingQuote quote = null;
    if (requiresShipping) {
        // System.out.println("** Berfore default shipping quote **");
        // Get all applicable shipping quotes
        quote = orderFacade.getShippingQuote(customer, cart, order, store, language);
        model.addAttribute("shippingQuote", quote);
    }
    if (quote != null) {
        String shippingReturnCode = quote.getShippingReturnCode();
        if (StringUtils.isBlank(shippingReturnCode) || shippingReturnCode.equals(ShippingQuote.NO_POSTAL_CODE)) {
            if (order.getShippingSummary() == null) {
                ShippingSummary summary = orderFacade.getShippingSummary(quote, store, language);
                order.setShippingSummary(summary);
                // TODO DTO
                request.getSession().setAttribute(Constants.SHIPPING_SUMMARY, summary);
            }
            if (order.getSelectedShippingOption() == null) {
                order.setSelectedShippingOption(quote.getSelectedShippingOption());
            }
            // save quotes in HttpSession
            List<ShippingOption> options = quote.getShippingOptions();
            // TODO DTO
            request.getSession().setAttribute(Constants.SHIPPING_OPTIONS, options);
            if (!CollectionUtils.isEmpty(options)) {
                for (ShippingOption shipOption : options) {
                    StringBuilder moduleName = new StringBuilder();
                    moduleName.append("module.shipping.").append(shipOption.getShippingModuleCode());
                    String carrier = messages.getMessage(moduleName.toString(), locale);
                    String note = messages.getMessage(moduleName.append(".note").toString(), locale, "");
                    shipOption.setDescription(carrier);
                    shipOption.setNote(note);
                    // option name
                    if (!StringUtils.isBlank(shipOption.getOptionCode())) {
                        // try to get the translate
                        StringBuilder optionCodeBuilder = new StringBuilder();
                        try {
                            optionCodeBuilder.append("module.shipping.").append(shipOption.getShippingModuleCode());
                            String optionName = messages.getMessage(optionCodeBuilder.toString(), locale);
                            shipOption.setOptionName(optionName);
                        } catch (Exception e) {
                            // label not found
                            LOGGER.warn("displayCheckout No shipping code found for " + optionCodeBuilder.toString());
                        }
                    }
                }
            }
        }
        if (quote.getDeliveryAddress() != null) {
            ReadableCustomerDeliveryAddressPopulator addressPopulator = new ReadableCustomerDeliveryAddressPopulator();
            addressPopulator.setCountryService(countryService);
            addressPopulator.setZoneService(zoneService);
            ReadableDelivery deliveryAddress = new ReadableDelivery();
            addressPopulator.populate(quote.getDeliveryAddress(), deliveryAddress, store, language);
            model.addAttribute("deliveryAddress", deliveryAddress);
            super.setSessionAttribute(Constants.KEY_SESSION_ADDRESS, deliveryAddress, request);
        }
        // get shipping countries
        List<Country> shippingCountriesList = orderFacade.getShipToCountry(store, language);
        model.addAttribute("countries", shippingCountriesList);
    } else {
        // get all countries
        List<Country> countries = countryService.getCountries(language);
        model.addAttribute("countries", countries);
    }
    if (quote != null && quote.getShippingReturnCode() != null && quote.getShippingReturnCode().equals(ShippingQuote.NO_SHIPPING_MODULE_CONFIGURED)) {
        LOGGER.error("Shipping quote error " + quote.getShippingReturnCode());
        model.addAttribute("errorMessages", messages.getMessage(quote.getShippingReturnCode(), locale, quote.getShippingReturnCode()));
    }
    if (quote != null && !StringUtils.isBlank(quote.getQuoteError())) {
        LOGGER.error("Shipping quote error " + quote.getQuoteError());
        model.addAttribute("errorMessages", quote.getQuoteError());
    }
    if (quote != null && quote.getShippingReturnCode() != null && quote.getShippingReturnCode().equals(ShippingQuote.NO_SHIPPING_TO_SELECTED_COUNTRY)) {
        LOGGER.error("Shipping quote error " + quote.getShippingReturnCode());
        model.addAttribute("errorMessages", quote.getShippingReturnCode());
    }
    /**
     * end shipping *
     */
    // get payment methods
    List<PaymentMethod> paymentMethods = paymentService.getAcceptedPaymentMethods(store);
    // not free and no payment methods
    if (CollectionUtils.isEmpty(paymentMethods) && !freeShoppingCart) {
        LOGGER.error("No payment method configured");
        model.addAttribute("errorMessages", messages.getMessage("payment.not.configured", locale, "No payments configured"));
    }
    if (!CollectionUtils.isEmpty(paymentMethods)) {
        // select default payment method
        PaymentMethod defaultPaymentSelected = null;
        for (PaymentMethod paymentMethod : paymentMethods) {
            if (paymentMethod.isDefaultSelected()) {
                defaultPaymentSelected = paymentMethod;
                break;
            }
        }
        if (defaultPaymentSelected == null) {
            // forced default selection
            defaultPaymentSelected = paymentMethods.get(0);
            defaultPaymentSelected.setDefaultSelected(true);
        }
        order.setDefaultPaymentMethodCode(defaultPaymentSelected.getPaymentMethodCode());
    }
    // readable shopping cart items for order summary box
    ShoppingCartData shoppingCart = shoppingCartFacade.getShoppingCartData(cart, language);
    model.addAttribute("cart", shoppingCart);
    order.setCartCode(shoppingCart.getCode());
    // order total
    OrderTotalSummary orderTotalSummary = orderFacade.calculateOrderTotal(store, order, language);
    order.setOrderTotalSummary(orderTotalSummary);
    // if order summary has to be re-used
    super.setSessionAttribute(Constants.ORDER_SUMMARY, orderTotalSummary, request);
    // display hacks
    if (!StringUtils.isBlank(googleMapsKey)) {
        model.addAttribute("fieldDisabled", "true");
        model.addAttribute("cssClass", "");
    } else {
        model.addAttribute("fieldDisabled", "false");
        model.addAttribute("cssClass", "required");
    }
    model.addAttribute("order", order);
    model.addAttribute("paymentMethods", paymentMethods);
    /**
     * template *
     */
    StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Checkout.checkout).append(".").append(store.getStoreTemplate());
    return template.toString();
}
Also used : AnonymousCustomer(com.salesmanager.shop.model.customer.AnonymousCustomer) Customer(com.salesmanager.core.model.customer.Customer) PersistableCustomer(com.salesmanager.shop.model.customer.PersistableCustomer) OrderTotalSummary(com.salesmanager.core.model.order.OrderTotalSummary) AnonymousCustomer(com.salesmanager.shop.model.customer.AnonymousCustomer) Product(com.salesmanager.core.model.catalog.product.Product) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) Language(com.salesmanager.core.model.reference.language.Language) ReadableCustomerDeliveryAddressPopulator(com.salesmanager.shop.populator.customer.ReadableCustomerDeliveryAddressPopulator) ShippingSummary(com.salesmanager.core.model.shipping.ShippingSummary) ReadableShippingSummary(com.salesmanager.shop.model.order.shipping.ReadableShippingSummary) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) HashSet(java.util.HashSet) FinalPrice(com.salesmanager.core.model.catalog.product.price.FinalPrice) Zone(com.salesmanager.core.model.reference.zone.Zone) ReadableDelivery(com.salesmanager.shop.model.customer.ReadableDelivery) ShoppingCartData(com.salesmanager.shop.model.shoppingcart.ShoppingCartData) ServiceException(com.salesmanager.core.business.exception.ServiceException) ShippingOption(com.salesmanager.core.model.shipping.ShippingOption) ShopOrder(com.salesmanager.shop.model.order.ShopOrder) ReadableShopOrder(com.salesmanager.shop.model.order.ReadableShopOrder) ShippingMetaData(com.salesmanager.core.model.shipping.ShippingMetaData) ShippingQuote(com.salesmanager.core.model.shipping.ShippingQuote) Billing(com.salesmanager.core.model.common.Billing) Country(com.salesmanager.core.model.reference.country.Country) PaymentMethod(com.salesmanager.core.model.payments.PaymentMethod) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with Billing

use of com.salesmanager.core.model.common.Billing in project shopizer by shopizer-ecommerce.

the class ShippingQuoteByWeightTest method testGetCustomShippingQuotesByWeight.

@Ignore
public // @Test
void testGetCustomShippingQuotesByWeight() throws ServiceException {
    Language en = languageService.getByCode("en");
    Country country = countryService.getByCode("CA");
    Zone zone = zoneService.getByCode("QC");
    MerchantStore store = merchantService.getByCode(MerchantStore.DEFAULT_STORE);
    ProductType generalType = productTypeService.getProductType(ProductType.GENERAL_TYPE);
    // set valid store postal code
    store.setStorepostalcode("J4B-9J9");
    Product product = new Product();
    product.setProductHeight(new BigDecimal(4));
    product.setProductLength(new BigDecimal(3));
    product.setProductWidth(new BigDecimal(5));
    product.setProductWeight(new BigDecimal(8));
    product.setSku("TESTSKU");
    product.setType(generalType);
    product.setMerchantStore(store);
    // Product description
    ProductDescription description = new ProductDescription();
    description.setName("Product 1");
    description.setLanguage(en);
    description.setProduct(product);
    product.getDescriptions().add(description);
    productService.create(product);
    // productService.saveOrUpdate(product);
    // Availability
    ProductAvailability availability = new ProductAvailability();
    availability.setProductDateAvailable(new Date());
    availability.setProductQuantity(100);
    availability.setRegion("*");
    // associate with product
    availability.setProduct(product);
    product.getAvailabilities().add(availability);
    productAvailabilityService.create(availability);
    ProductPrice dprice = new ProductPrice();
    dprice.setDefaultPrice(true);
    dprice.setProductPriceAmount(new BigDecimal(29.99));
    dprice.setProductAvailability(availability);
    ProductPriceDescription dpd = new ProductPriceDescription();
    dpd.setName("Base price");
    dpd.setProductPrice(dprice);
    dpd.setLanguage(en);
    dprice.getDescriptions().add(dpd);
    availability.getPrices().add(dprice);
    productPriceService.create(dprice);
    // get product
    product = productService.getByCode("TESTSKU", en);
    // check the product
    Set<ProductAvailability> avails = product.getAvailabilities();
    for (ProductAvailability as : avails) {
        Set<ProductPrice> availabilityPrices = as.getPrices();
        for (ProductPrice ps : availabilityPrices) {
            System.out.println(ps.getProductPriceAmount().toString());
        }
    }
    // check availability
    Set<ProductPrice> availabilityPrices = availability.getPrices();
    for (ProductPrice ps : availabilityPrices) {
        System.out.println(ps.getProductPriceAmount().toString());
    }
    // configure shipping
    ShippingConfiguration shippingConfiguration = new ShippingConfiguration();
    // based on shipping or billing address
    shippingConfiguration.setShippingBasisType(ShippingBasisType.SHIPPING);
    shippingConfiguration.setShippingType(ShippingType.INTERNATIONAL);
    // individual item pricing or box packaging (see unit test above)
    shippingConfiguration.setShippingPackageType(ShippingPackageType.ITEM);
    // only if package type is package
    shippingConfiguration.setBoxHeight(5);
    shippingConfiguration.setBoxLength(5);
    shippingConfiguration.setBoxWidth(5);
    shippingConfiguration.setBoxWeight(1);
    shippingConfiguration.setMaxWeight(10);
    List<String> supportedCountries = new ArrayList<String>();
    supportedCountries.add("CA");
    supportedCountries.add("US");
    supportedCountries.add("UK");
    supportedCountries.add("FR");
    shippingService.setSupportedCountries(store, supportedCountries);
    CustomShippingQuotesConfiguration customConfiguration = new CustomShippingQuotesConfiguration();
    customConfiguration.setModuleCode("weightBased");
    customConfiguration.setActive(true);
    CustomShippingQuotesRegion northRegion = new CustomShippingQuotesRegion();
    northRegion.setCustomRegionName("NORTH");
    List<String> countries = new ArrayList<String>();
    countries.add("CA");
    countries.add("US");
    northRegion.setCountries(countries);
    CustomShippingQuoteWeightItem caQuote4 = new CustomShippingQuoteWeightItem();
    caQuote4.setMaximumWeight(4);
    caQuote4.setPrice(new BigDecimal(20));
    CustomShippingQuoteWeightItem caQuote10 = new CustomShippingQuoteWeightItem();
    caQuote10.setMaximumWeight(10);
    caQuote10.setPrice(new BigDecimal(50));
    CustomShippingQuoteWeightItem caQuote100 = new CustomShippingQuoteWeightItem();
    caQuote100.setMaximumWeight(100);
    caQuote100.setPrice(new BigDecimal(120));
    List<CustomShippingQuoteWeightItem> quotes = new ArrayList<CustomShippingQuoteWeightItem>();
    quotes.add(caQuote4);
    quotes.add(caQuote10);
    quotes.add(caQuote100);
    northRegion.setQuoteItems(quotes);
    customConfiguration.getRegions().add(northRegion);
    // create an integration configuration - USPS
    IntegrationConfiguration configuration = new IntegrationConfiguration();
    configuration.setActive(true);
    configuration.setEnvironment(Environment.TEST.name());
    configuration.setModuleCode("weightBased");
    // configure module
    shippingService.saveShippingConfiguration(shippingConfiguration, store);
    // create the basic configuration
    shippingService.saveShippingQuoteModuleConfiguration(configuration, store);
    // and the custom configuration
    shippingService.saveCustomShippingConfiguration("weightBased", customConfiguration, store);
    // now create ShippingProduct
    ShippingProduct shippingProduct1 = new ShippingProduct(product);
    FinalPrice price = pricingService.calculateProductPrice(product);
    shippingProduct1.setFinalPrice(price);
    List<ShippingProduct> shippingProducts = new ArrayList<ShippingProduct>();
    shippingProducts.add(shippingProduct1);
    Customer customer = new Customer();
    customer.setMerchantStore(store);
    customer.setEmailAddress("test@test.com");
    customer.setGender(CustomerGender.M);
    customer.setDefaultLanguage(en);
    customer.setAnonymous(true);
    customer.setCompany("ifactory");
    customer.setDateOfBirth(new Date());
    customer.setNick("My nick");
    customer.setPassword("123456");
    Delivery delivery = new Delivery();
    delivery.setAddress("Shipping address");
    delivery.setCity("Boucherville");
    delivery.setCountry(country);
    delivery.setZone(zone);
    delivery.setPostalCode("J5C-6J4");
    // overwrite delivery to US
    /*	    delivery.setPostalCode("90002");
	    delivery.setCountry(us);
	    Zone california = zoneService.getByCode("CA");
	    delivery.setZone(california);*/
    Billing billing = new Billing();
    billing.setAddress("Billing address");
    billing.setCountry(country);
    billing.setZone(zone);
    billing.setPostalCode("J4B-8J9");
    billing.setFirstName("Carl");
    billing.setLastName("Samson");
    customer.setBilling(billing);
    customer.setDelivery(delivery);
    customerService.create(customer);
    // for correlation
    Long dummyCartId = 0L;
    ShippingQuote shippingQuote = shippingService.getShippingQuote(dummyCartId, store, delivery, shippingProducts, en);
    Assert.notNull(shippingQuote);
}
Also used : Customer(com.salesmanager.core.model.customer.Customer) ArrayList(java.util.ArrayList) ShippingProduct(com.salesmanager.core.model.shipping.ShippingProduct) Product(com.salesmanager.core.model.catalog.product.Product) ProductPrice(com.salesmanager.core.model.catalog.product.price.ProductPrice) ShippingConfiguration(com.salesmanager.core.model.shipping.ShippingConfiguration) Language(com.salesmanager.core.model.reference.language.Language) ProductAvailability(com.salesmanager.core.model.catalog.product.availability.ProductAvailability) CustomShippingQuoteWeightItem(com.salesmanager.core.modules.integration.shipping.model.CustomShippingQuoteWeightItem) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) ProductPriceDescription(com.salesmanager.core.model.catalog.product.price.ProductPriceDescription) FinalPrice(com.salesmanager.core.model.catalog.product.price.FinalPrice) CustomShippingQuotesConfiguration(com.salesmanager.core.modules.integration.shipping.model.CustomShippingQuotesConfiguration) Zone(com.salesmanager.core.model.reference.zone.Zone) CustomShippingQuotesRegion(com.salesmanager.core.modules.integration.shipping.model.CustomShippingQuotesRegion) IntegrationConfiguration(com.salesmanager.core.model.system.IntegrationConfiguration) ProductType(com.salesmanager.core.model.catalog.product.type.ProductType) ShippingProduct(com.salesmanager.core.model.shipping.ShippingProduct) BigDecimal(java.math.BigDecimal) Date(java.util.Date) ShippingQuote(com.salesmanager.core.model.shipping.ShippingQuote) Billing(com.salesmanager.core.model.common.Billing) Country(com.salesmanager.core.model.reference.country.Country) ProductDescription(com.salesmanager.core.model.catalog.product.description.ProductDescription) Delivery(com.salesmanager.core.model.common.Delivery) Ignore(org.junit.Ignore)

Example 3 with Billing

use of com.salesmanager.core.model.common.Billing in project shopizer by shopizer-ecommerce.

the class CustomerTest method createCustomer.

@Test
public void createCustomer() throws ServiceException {
    Language en = languageService.getByCode("en");
    MerchantStore store = merchantService.getByCode(MerchantStore.DEFAULT_STORE);
    Country country = countryService.getByCode("CA");
    Zone zone = zoneService.getByCode("QC");
    /**
     * Core customer attributes *
     */
    Customer customer = new Customer();
    customer.setMerchantStore(store);
    customer.setEmailAddress("test@test.com");
    customer.setGender(CustomerGender.M);
    customer.setAnonymous(true);
    customer.setCompany("ifactory");
    customer.setDateOfBirth(new Date());
    customer.setNick("My nick");
    customer.setPassword("123456");
    customer.setDefaultLanguage(store.getDefaultLanguage());
    Delivery delivery = new Delivery();
    delivery.setAddress("Shipping address");
    delivery.setCountry(country);
    delivery.setZone(zone);
    Billing billing = new Billing();
    billing.setFirstName("John");
    billing.setLastName("Bossanova");
    billing.setAddress("Billing address");
    billing.setCountry(country);
    billing.setZone(zone);
    customer.setBilling(billing);
    customer.setDelivery(delivery);
    customerService.create(customer);
    customer = customerService.getById(customer.getId());
    // create an option value
    CustomerOptionValue yes = new CustomerOptionValue();
    yes.setCode("yes");
    yes.setMerchantStore(store);
    CustomerOptionValueDescription yesDescription = new CustomerOptionValueDescription();
    yesDescription.setLanguage(en);
    yesDescription.setCustomerOptionValue(yes);
    CustomerOptionValueDescription yes_sir = new CustomerOptionValueDescription();
    yes_sir.setCustomerOptionValue(yes);
    yes_sir.setDescription("Yes sir!");
    yes_sir.setName("Yes sir!");
    yes_sir.setLanguage(en);
    yes.getDescriptions().add(yes_sir);
    // needs to be saved before using it
    customerOptionValueService.create(yes);
    CustomerOptionValue no = new CustomerOptionValue();
    no.setCode("no");
    no.setMerchantStore(store);
    CustomerOptionValueDescription noDescription = new CustomerOptionValueDescription();
    noDescription.setLanguage(en);
    noDescription.setCustomerOptionValue(no);
    CustomerOptionValueDescription no_sir = new CustomerOptionValueDescription();
    no_sir.setCustomerOptionValue(no);
    no_sir.setDescription("Nope!");
    no_sir.setName("Nope!");
    no_sir.setLanguage(en);
    no.getDescriptions().add(no_sir);
    // needs to be saved before using it
    customerOptionValueService.create(no);
    // create a customer option to be used
    CustomerOption subscribedToMailingList = new CustomerOption();
    subscribedToMailingList.setActive(true);
    subscribedToMailingList.setPublicOption(true);
    subscribedToMailingList.setCode("subscribedToMailingList");
    subscribedToMailingList.setMerchantStore(store);
    CustomerOptionDescription mailingListDesciption = new CustomerOptionDescription();
    mailingListDesciption.setName("Subscribed to mailing list");
    mailingListDesciption.setDescription("Subscribed to mailing list");
    mailingListDesciption.setLanguage(en);
    mailingListDesciption.setCustomerOption(subscribedToMailingList);
    Set<CustomerOptionDescription> mailingListDesciptionList = new HashSet<CustomerOptionDescription>();
    mailingListDesciptionList.add(mailingListDesciption);
    subscribedToMailingList.setDescriptions(mailingListDesciptionList);
    customerOptionService.create(subscribedToMailingList);
    // create a customer option to be used
    CustomerOption hasReturnedItems = new CustomerOption();
    hasReturnedItems.setActive(true);
    hasReturnedItems.setPublicOption(true);
    hasReturnedItems.setCode("hasReturnedItems");
    hasReturnedItems.setMerchantStore(store);
    CustomerOptionDescription hasReturnedItemsDesciption = new CustomerOptionDescription();
    hasReturnedItemsDesciption.setName("Has returned items");
    hasReturnedItemsDesciption.setDescription("Has returned items");
    hasReturnedItemsDesciption.setLanguage(en);
    hasReturnedItemsDesciption.setCustomerOption(hasReturnedItems);
    Set<CustomerOptionDescription> hasReturnedItemsList = new HashSet<CustomerOptionDescription>();
    hasReturnedItemsList.add(hasReturnedItemsDesciption);
    hasReturnedItems.setDescriptions(hasReturnedItemsList);
    customerOptionService.create(hasReturnedItems);
    subscribedToMailingList.setSortOrder(3);
    customerOptionService.update(subscribedToMailingList);
    // --
    // now create an option set (association of a customer option with possible customer option values)
    // --
    // possible yes
    CustomerOptionSet mailingListSetYes = new CustomerOptionSet();
    mailingListSetYes.setSortOrder(0);
    mailingListSetYes.setCustomerOption(subscribedToMailingList);
    mailingListSetYes.setCustomerOptionValue(yes);
    customerOptionSetService.create(mailingListSetYes);
    // possible no
    CustomerOptionSet mailingListSetNo = new CustomerOptionSet();
    // mailingListSetNo.setPk(mailingListSetNoId);
    mailingListSetNo.setSortOrder(1);
    mailingListSetNo.setCustomerOption(subscribedToMailingList);
    mailingListSetNo.setCustomerOptionValue(no);
    customerOptionSetService.create(mailingListSetNo);
    // possible has returned items
    CustomerOptionSet hasReturnedItemsYes = new CustomerOptionSet();
    hasReturnedItemsYes.setSortOrder(0);
    hasReturnedItemsYes.setCustomerOption(hasReturnedItems);
    hasReturnedItemsYes.setCustomerOptionValue(yes);
    customerOptionSetService.create(hasReturnedItemsYes);
    subscribedToMailingList.setSortOrder(2);
    customerOptionService.update(subscribedToMailingList);
    CustomerOption option = customerOptionService.getById(subscribedToMailingList.getId());
    option.setSortOrder(4);
    customerOptionService.update(option);
    List<CustomerOptionSet> optionSetList = customerOptionSetService.listByStore(store, en);
    // Assert.assertEquals(3, optionSetList.size());
    System.out.println("Size of options : " + optionSetList.size());
    /**
     * Now create a customer option attribute
     * A customer attribute is a selected customer option set transformed to an
     * attribute for a given customer
     */
    CustomerAttribute customerAttributeMailingList = new CustomerAttribute();
    customerAttributeMailingList.setCustomer(customer);
    customerAttributeMailingList.setCustomerOption(subscribedToMailingList);
    customerAttributeMailingList.setCustomerOptionValue(no);
    customer.getAttributes().add(customerAttributeMailingList);
    customerService.save(customer);
    customerService.delete(customer);
}
Also used : CustomerOptionDescription(com.salesmanager.core.model.customer.attribute.CustomerOptionDescription) Customer(com.salesmanager.core.model.customer.Customer) Zone(com.salesmanager.core.model.reference.zone.Zone) CustomerOptionSet(com.salesmanager.core.model.customer.attribute.CustomerOptionSet) Date(java.util.Date) CustomerOption(com.salesmanager.core.model.customer.attribute.CustomerOption) CustomerOptionValue(com.salesmanager.core.model.customer.attribute.CustomerOptionValue) Language(com.salesmanager.core.model.reference.language.Language) CustomerAttribute(com.salesmanager.core.model.customer.attribute.CustomerAttribute) Billing(com.salesmanager.core.model.common.Billing) Country(com.salesmanager.core.model.reference.country.Country) CustomerOptionValueDescription(com.salesmanager.core.model.customer.attribute.CustomerOptionValueDescription) Delivery(com.salesmanager.core.model.common.Delivery) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 4 with Billing

use of com.salesmanager.core.model.common.Billing in project shopizer by shopizer-ecommerce.

the class PersistableOrderApiPopulator method populate.

@Override
public Order populate(PersistableOrder source, Order target, MerchantStore store, Language language) throws ConversionException {
    /*		Validate.notNull(currencyService,"currencyService must be set");
		Validate.notNull(customerService,"customerService must be set");
		Validate.notNull(shoppingCartService,"shoppingCartService must be set");
		Validate.notNull(productService,"productService must be set");
		Validate.notNull(productAttributeService,"productAttributeService must be set");
		Validate.notNull(digitalProductService,"digitalProductService must be set");*/
    Validate.notNull(source.getPayment(), "Payment cannot be null");
    try {
        if (target == null) {
            target = new Order();
        }
        // target.setLocale(LocaleUtils.getLocale(store));
        target.setLocale(LocaleUtils.getLocale(store));
        Currency currency = null;
        try {
            currency = currencyService.getByCode(source.getCurrency());
        } catch (Exception e) {
            throw new ConversionException("Currency not found for code " + source.getCurrency());
        }
        if (currency == null) {
            throw new ConversionException("Currency not found for code " + source.getCurrency());
        }
        // Customer
        Customer customer = null;
        if (source.getCustomerId() != null && source.getCustomerId().longValue() > 0) {
            Long customerId = source.getCustomerId();
            customer = customerService.getById(customerId);
            if (customer == null) {
                throw new ConversionException("Curstomer with id " + source.getCustomerId() + " does not exist");
            }
            target.setCustomerId(customerId);
        } else {
            if (source instanceof PersistableAnonymousOrder) {
                PersistableCustomer persistableCustomer = ((PersistableAnonymousOrder) source).getCustomer();
                customer = new Customer();
                customer = customerPopulator.populate(persistableCustomer, customer, store, language);
            } else {
                throw new ConversionException("Curstomer details or id not set in request");
            }
        }
        target.setCustomerEmailAddress(customer.getEmailAddress());
        Delivery delivery = customer.getDelivery();
        target.setDelivery(delivery);
        Billing billing = customer.getBilling();
        target.setBilling(billing);
        if (source.getAttributes() != null && source.getAttributes().size() > 0) {
            Set<OrderAttribute> attrs = new HashSet<OrderAttribute>();
            for (com.salesmanager.shop.model.order.OrderAttribute attribute : source.getAttributes()) {
                OrderAttribute attr = new OrderAttribute();
                attr.setKey(attribute.getKey());
                attr.setValue(attribute.getValue());
                attr.setOrder(target);
                attrs.add(attr);
            }
            target.setOrderAttributes(attrs);
        }
        target.setDatePurchased(new Date());
        target.setCurrency(currency);
        target.setCurrencyValue(new BigDecimal(0));
        target.setMerchant(store);
        target.setChannel(OrderChannel.API);
        // need this
        target.setStatus(OrderStatus.ORDERED);
        target.setPaymentModuleCode(source.getPayment().getPaymentModule());
        target.setPaymentType(PaymentType.valueOf(source.getPayment().getPaymentType()));
        target.setCustomerAgreement(source.isCustomerAgreement());
        // force this to true, cannot perform this activity from the API
        target.setConfirmedAddress(true);
        if (!StringUtils.isBlank(source.getComments())) {
            OrderStatusHistory statusHistory = new OrderStatusHistory();
            statusHistory.setStatus(null);
            statusHistory.setOrder(target);
            statusHistory.setComments(source.getComments());
            target.getOrderHistory().add(statusHistory);
        }
        return target;
    } catch (Exception e) {
        throw new ConversionException(e);
    }
}
Also used : PersistableAnonymousOrder(com.salesmanager.shop.model.order.v1.PersistableAnonymousOrder) Order(com.salesmanager.core.model.order.Order) PersistableOrder(com.salesmanager.shop.model.order.v1.PersistableOrder) ConversionException(com.salesmanager.core.business.exception.ConversionException) Customer(com.salesmanager.core.model.customer.Customer) PersistableCustomer(com.salesmanager.shop.model.customer.PersistableCustomer) PersistableCustomer(com.salesmanager.shop.model.customer.PersistableCustomer) ConversionException(com.salesmanager.core.business.exception.ConversionException) Date(java.util.Date) BigDecimal(java.math.BigDecimal) Currency(com.salesmanager.core.model.reference.currency.Currency) Billing(com.salesmanager.core.model.common.Billing) OrderAttribute(com.salesmanager.core.model.order.attributes.OrderAttribute) PersistableAnonymousOrder(com.salesmanager.shop.model.order.v1.PersistableAnonymousOrder) Delivery(com.salesmanager.core.model.common.Delivery) OrderStatusHistory(com.salesmanager.core.model.order.orderstatus.OrderStatusHistory) HashSet(java.util.HashSet)

Example 5 with Billing

use of com.salesmanager.core.model.common.Billing in project shopizer by shopizer-ecommerce.

the class CustomerPopulator method populate.

/**
 * Creates a Customer entity ready to be saved
 */
@Override
public Customer populate(PersistableCustomer source, Customer target, MerchantStore store, Language language) throws ConversionException {
    try {
        if (source.getId() != null && source.getId() > 0) {
            target.setId(source.getId());
        }
        if (!StringUtils.isBlank(source.getPassword())) {
            target.setPassword(passwordEncoder.encode(source.getPassword()));
            target.setNick(source.getUserName());
            target.setAnonymous(false);
        }
        if (source.getBilling() != null) {
            target.setBilling(new Billing());
            if (!StringUtils.isEmpty(source.getFirstName())) {
                target.getBilling().setFirstName(source.getFirstName());
            }
            if (!StringUtils.isEmpty(source.getLastName())) {
                target.getBilling().setLastName(source.getLastName());
            }
        }
        if (!StringUtils.isBlank(source.getProvider())) {
            target.setProvider(source.getProvider());
        }
        if (!StringUtils.isBlank(source.getEmailAddress())) {
            target.setEmailAddress(source.getEmailAddress());
        }
        if (source.getGender() != null && target.getGender() == null) {
            target.setGender(com.salesmanager.core.model.customer.CustomerGender.valueOf(source.getGender()));
        }
        if (target.getGender() == null) {
            target.setGender(com.salesmanager.core.model.customer.CustomerGender.M);
        }
        Map<String, Country> countries = countryService.getCountriesMap(language);
        Map<String, Zone> zones = zoneService.getZones(language);
        target.setMerchantStore(store);
        Address sourceBilling = source.getBilling();
        if (sourceBilling != null) {
            Billing billing = target.getBilling();
            billing.setAddress(sourceBilling.getAddress());
            billing.setCity(sourceBilling.getCity());
            billing.setCompany(sourceBilling.getCompany());
            // billing.setCountry(country);
            if (!StringUtils.isEmpty(sourceBilling.getFirstName()))
                billing.setFirstName(sourceBilling.getFirstName());
            if (!StringUtils.isEmpty(sourceBilling.getLastName()))
                billing.setLastName(sourceBilling.getLastName());
            billing.setTelephone(sourceBilling.getPhone());
            billing.setPostalCode(sourceBilling.getPostalCode());
            billing.setState(sourceBilling.getStateProvince());
            Country billingCountry = null;
            if (!StringUtils.isBlank(sourceBilling.getCountry())) {
                billingCountry = countries.get(sourceBilling.getCountry());
                if (billingCountry == null) {
                    throw new ConversionException("Unsuported country code " + sourceBilling.getCountry());
                }
                billing.setCountry(billingCountry);
            }
            if (billingCountry != null && !StringUtils.isBlank(sourceBilling.getZone())) {
                Zone zone = zoneService.getByCode(sourceBilling.getZone());
                if (zone == null) {
                    throw new ConversionException("Unsuported zone code " + sourceBilling.getZone());
                }
                Zone zoneDescription = zones.get(zone.getCode());
                billing.setZone(zoneDescription);
            }
        // target.setBilling(billing);
        }
        if (target.getBilling() == null && source.getBilling() != null) {
            LOG.info("Setting default values for billing");
            Billing billing = new Billing();
            Country billingCountry = null;
            if (StringUtils.isNotBlank(source.getBilling().getCountry())) {
                billingCountry = countries.get(source.getBilling().getCountry());
                if (billingCountry == null) {
                    throw new ConversionException("Unsuported country code " + sourceBilling.getCountry());
                }
                billing.setCountry(billingCountry);
                target.setBilling(billing);
            }
        }
        Address sourceShipping = source.getDelivery();
        if (sourceShipping != null) {
            Delivery delivery = new Delivery();
            delivery.setAddress(sourceShipping.getAddress());
            delivery.setCity(sourceShipping.getCity());
            delivery.setCompany(sourceShipping.getCompany());
            delivery.setFirstName(sourceShipping.getFirstName());
            delivery.setLastName(sourceShipping.getLastName());
            delivery.setTelephone(sourceShipping.getPhone());
            delivery.setPostalCode(sourceShipping.getPostalCode());
            delivery.setState(sourceShipping.getStateProvince());
            Country deliveryCountry = null;
            if (!StringUtils.isBlank(sourceShipping.getCountry())) {
                deliveryCountry = countries.get(sourceShipping.getCountry());
                if (deliveryCountry == null) {
                    throw new ConversionException("Unsuported country code " + sourceShipping.getCountry());
                }
                delivery.setCountry(deliveryCountry);
            }
            if (deliveryCountry != null && !StringUtils.isBlank(sourceShipping.getZone())) {
                Zone zone = zoneService.getByCode(sourceShipping.getZone());
                if (zone == null) {
                    throw new ConversionException("Unsuported zone code " + sourceShipping.getZone());
                }
                Zone zoneDescription = zones.get(zone.getCode());
                delivery.setZone(zoneDescription);
            }
            target.setDelivery(delivery);
        }
        if (source.getRating() != null && source.getRating().doubleValue() > 0) {
            target.setCustomerReviewAvg(new BigDecimal(source.getRating().doubleValue()));
        }
        if (source.getRatingCount() > 0) {
            target.setCustomerReviewCount(source.getRatingCount());
        }
        if (target.getDelivery() == null && source.getDelivery() != null) {
            LOG.info("Setting default value for delivery");
            Delivery delivery = new Delivery();
            Country deliveryCountry = null;
            if (StringUtils.isNotBlank(source.getDelivery().getCountry())) {
                deliveryCountry = countries.get(source.getDelivery().getCountry());
                if (deliveryCountry == null) {
                    throw new ConversionException("Unsuported country code " + sourceShipping.getCountry());
                }
                delivery.setCountry(deliveryCountry);
                target.setDelivery(delivery);
            }
        }
        if (source.getAttributes() != null) {
            for (PersistableCustomerAttribute attr : source.getAttributes()) {
                CustomerOption customerOption = customerOptionService.getById(attr.getCustomerOption().getId());
                if (customerOption == null) {
                    throw new ConversionException("Customer option id " + attr.getCustomerOption().getId() + " does not exist");
                }
                CustomerOptionValue customerOptionValue = customerOptionValueService.getById(attr.getCustomerOptionValue().getId());
                if (customerOptionValue == null) {
                    throw new ConversionException("Customer option value id " + attr.getCustomerOptionValue().getId() + " does not exist");
                }
                if (customerOption.getMerchantStore().getId().intValue() != store.getId().intValue()) {
                    throw new ConversionException("Invalid customer option id ");
                }
                if (customerOptionValue.getMerchantStore().getId().intValue() != store.getId().intValue()) {
                    throw new ConversionException("Invalid customer option value id ");
                }
                CustomerAttribute attribute = new CustomerAttribute();
                attribute.setCustomer(target);
                attribute.setCustomerOption(customerOption);
                attribute.setCustomerOptionValue(customerOptionValue);
                attribute.setTextValue(attr.getTextValue());
                target.getAttributes().add(attribute);
            }
        }
        if (target.getDefaultLanguage() == null) {
            Language lang = source.getLanguage() == null ? language : languageService.getByCode(source.getLanguage());
            target.setDefaultLanguage(lang);
        }
    } catch (Exception e) {
        throw new ConversionException(e);
    }
    return target;
}
Also used : ConversionException(com.salesmanager.core.business.exception.ConversionException) Address(com.salesmanager.shop.model.customer.address.Address) Zone(com.salesmanager.core.model.reference.zone.Zone) BigDecimal(java.math.BigDecimal) ConversionException(com.salesmanager.core.business.exception.ConversionException) CustomerOption(com.salesmanager.core.model.customer.attribute.CustomerOption) CustomerOptionValue(com.salesmanager.core.model.customer.attribute.CustomerOptionValue) Language(com.salesmanager.core.model.reference.language.Language) PersistableCustomerAttribute(com.salesmanager.shop.model.customer.attribute.PersistableCustomerAttribute) CustomerAttribute(com.salesmanager.core.model.customer.attribute.CustomerAttribute) Billing(com.salesmanager.core.model.common.Billing) Country(com.salesmanager.core.model.reference.country.Country) Delivery(com.salesmanager.core.model.common.Delivery) PersistableCustomerAttribute(com.salesmanager.shop.model.customer.attribute.PersistableCustomerAttribute)

Aggregations

Billing (com.salesmanager.core.model.common.Billing)12 Delivery (com.salesmanager.core.model.common.Delivery)10 Customer (com.salesmanager.core.model.customer.Customer)7 Country (com.salesmanager.core.model.reference.country.Country)6 Zone (com.salesmanager.core.model.reference.zone.Zone)6 Language (com.salesmanager.core.model.reference.language.Language)5 ShippingQuote (com.salesmanager.core.model.shipping.ShippingQuote)5 BigDecimal (java.math.BigDecimal)5 MerchantStore (com.salesmanager.core.model.merchant.MerchantStore)4 ShippingProduct (com.salesmanager.core.model.shipping.ShippingProduct)4 PersistableCustomer (com.salesmanager.shop.model.customer.PersistableCustomer)4 Product (com.salesmanager.core.model.catalog.product.Product)3 Date (java.util.Date)3 HashSet (java.util.HashSet)3 ConversionException (com.salesmanager.core.business.exception.ConversionException)2 ProductAvailability (com.salesmanager.core.model.catalog.product.availability.ProductAvailability)2 ProductDescription (com.salesmanager.core.model.catalog.product.description.ProductDescription)2 FinalPrice (com.salesmanager.core.model.catalog.product.price.FinalPrice)2 ProductPrice (com.salesmanager.core.model.catalog.product.price.ProductPrice)2 ProductPriceDescription (com.salesmanager.core.model.catalog.product.price.ProductPriceDescription)2