Search in sources :

Example 26 with Country

use of com.salesmanager.core.model.reference.country.Country in project shopizer by shopizer-ecommerce.

the class OrderTest method getMerchantOrders.

@Test
public void getMerchantOrders() throws ServiceException {
    Currency currency = currencyService.getByCode(USD_CURRENCY_CODE);
    Country country = countryService.getByCode("US");
    Zone zone = zoneService.getByCode("VT");
    Language en = languageService.getByCode("en");
    MerchantStore merchant = merchantService.getByCode(MerchantStore.DEFAULT_STORE);
    /**
     * Create a customer *
     */
    Customer customer = new Customer();
    customer.setMerchantStore(merchant);
    customer.setDefaultLanguage(en);
    customer.setEmailAddress("email@email.com");
    customer.setPassword("-1999");
    customer.setNick("My New nick");
    customer.setCompany(" Apple");
    customer.setGender(CustomerGender.M);
    customer.setDateOfBirth(new Date());
    Billing billing = new Billing();
    billing.setAddress("Billing address");
    billing.setCity("Billing city");
    billing.setCompany("Billing company");
    billing.setCountry(country);
    billing.setFirstName("Carl");
    billing.setLastName("Samson");
    billing.setPostalCode("Billing postal code");
    billing.setState("Billing state");
    billing.setZone(zone);
    Delivery delivery = new Delivery();
    delivery.setAddress("Shipping address");
    delivery.setCountry(country);
    delivery.setZone(zone);
    customer.setBilling(billing);
    customer.setDelivery(delivery);
    customerService.create(customer);
    // create a product with attributes
    /**
     * CATALOG CREATION *
     */
    ProductType generalType = productTypeService.getProductType(ProductType.GENERAL_TYPE);
    /**
     * Create the category
     */
    Category shirts = new Category();
    shirts.setMerchantStore(merchant);
    shirts.setCode("shirts");
    CategoryDescription shirtsEnglishDescription = new CategoryDescription();
    shirtsEnglishDescription.setName("Shirts");
    shirtsEnglishDescription.setCategory(shirts);
    shirtsEnglishDescription.setLanguage(en);
    Set<CategoryDescription> descriptions = new HashSet<CategoryDescription>();
    descriptions.add(shirtsEnglishDescription);
    shirts.setDescriptions(descriptions);
    categoryService.create(shirts);
    /**
     * Create a manufacturer
     */
    Manufacturer addidas = new Manufacturer();
    addidas.setMerchantStore(merchant);
    addidas.setCode("addidas");
    ManufacturerDescription addidasDesc = new ManufacturerDescription();
    addidasDesc.setLanguage(en);
    addidasDesc.setManufacturer(addidas);
    addidasDesc.setName("Addidas");
    addidas.getDescriptions().add(addidasDesc);
    manufacturerService.create(addidas);
    /**
     * Create an option
     */
    ProductOption option = new ProductOption();
    option.setMerchantStore(merchant);
    option.setCode("color");
    option.setProductOptionType(ProductOptionType.Radio.name());
    ProductOptionDescription optionDescription = new ProductOptionDescription();
    optionDescription.setLanguage(en);
    optionDescription.setName("Color");
    optionDescription.setDescription("Item color");
    optionDescription.setProductOption(option);
    option.getDescriptions().add(optionDescription);
    productOptionService.saveOrUpdate(option);
    /**
     * first option value *
     */
    ProductOptionValue white = new ProductOptionValue();
    white.setMerchantStore(merchant);
    white.setCode("white");
    ProductOptionValueDescription whiteDescription = new ProductOptionValueDescription();
    whiteDescription.setLanguage(en);
    whiteDescription.setName("White");
    whiteDescription.setDescription("White color");
    whiteDescription.setProductOptionValue(white);
    white.getDescriptions().add(whiteDescription);
    productOptionValueService.saveOrUpdate(white);
    ProductOptionValue black = new ProductOptionValue();
    black.setMerchantStore(merchant);
    black.setCode("black");
    /**
     * second option value *
     */
    ProductOptionValueDescription blackDesc = new ProductOptionValueDescription();
    blackDesc.setLanguage(en);
    blackDesc.setName("Black");
    blackDesc.setDescription("Black color");
    blackDesc.setProductOptionValue(black);
    black.getDescriptions().add(blackDesc);
    productOptionValueService.saveOrUpdate(black);
    /**
     * Create a complex product
     */
    Product product = new Product();
    product.setProductHeight(new BigDecimal(4));
    product.setProductLength(new BigDecimal(3));
    product.setProductWidth(new BigDecimal(1));
    product.setSku("TB12345");
    product.setManufacturer(addidas);
    product.setType(generalType);
    product.setMerchantStore(merchant);
    // Product description
    ProductDescription description = new ProductDescription();
    description.setName("Short sleeves shirt");
    description.setLanguage(en);
    description.setProduct(product);
    product.getDescriptions().add(description);
    product.getCategories().add(shirts);
    // availability
    ProductAvailability availability = new ProductAvailability();
    availability.setProductDateAvailable(new Date());
    availability.setProductQuantity(100);
    availability.setRegion("*");
    // associate with product
    availability.setProduct(product);
    // price
    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);
    product.getAvailabilities().add(availability);
    // attributes
    // white
    ProductAttribute whiteAttribute = new ProductAttribute();
    whiteAttribute.setProduct(product);
    whiteAttribute.setProductOption(option);
    whiteAttribute.setAttributeDefault(true);
    // no price variation
    whiteAttribute.setProductAttributePrice(new BigDecimal(0));
    // no weight variation
    whiteAttribute.setProductAttributeWeight(new BigDecimal(0));
    whiteAttribute.setProductOption(option);
    whiteAttribute.setProductOptionValue(white);
    product.getAttributes().add(whiteAttribute);
    // black
    ProductAttribute blackAttribute = new ProductAttribute();
    blackAttribute.setProduct(product);
    blackAttribute.setProductOption(option);
    // 5 + dollars
    blackAttribute.setProductAttributePrice(new BigDecimal(5));
    // no weight variation
    blackAttribute.setProductAttributeWeight(new BigDecimal(0));
    blackAttribute.setProductOption(option);
    blackAttribute.setProductOptionValue(black);
    product.getAttributes().add(blackAttribute);
    productService.create(product);
    /**
     * Create an order *
     */
    Order order = new Order();
    /**
     * payment details *
     */
    CreditCard creditCard = new CreditCard();
    creditCard.setCardType(CreditCardType.VISA);
    creditCard.setCcCvv("123");
    creditCard.setCcExpires("12/30/2020");
    creditCard.setCcNumber("123456789");
    creditCard.setCcOwner("ccOwner");
    order.setCreditCard(creditCard);
    /**
     * order core attributes *
     */
    order.setDatePurchased(new Date());
    order.setCurrency(currency);
    order.setMerchant(merchant);
    order.setLastModified(new Date());
    // no price variation because of the currency
    order.setCurrencyValue(new BigDecimal(1));
    order.setCustomerId(1L);
    order.setDelivery(delivery);
    order.setIpAddress("ipAddress");
    order.setMerchant(merchant);
    order.setOrderDateFinished(new Date());
    order.setPaymentType(PaymentType.CREDITCARD);
    order.setPaymentModuleCode("payment Module Code");
    order.setShippingModuleCode("UPS");
    order.setStatus(OrderStatus.ORDERED);
    order.setCustomerAgreement(true);
    order.setConfirmedAddress(true);
    order.setTotal(dprice.getProductPriceAmount());
    order.setCustomerEmailAddress(customer.getEmailAddress());
    order.setBilling(billing);
    order.setDelivery(delivery);
    /**
     * ORDER PRODUCT *
     */
    // OrderProduct
    OrderProduct oproduct = new OrderProduct();
    oproduct.setDownloads(null);
    oproduct.setOneTimeCharge(dprice.getProductPriceAmount());
    oproduct.setOrder(order);
    oproduct.setProductName(description.getName());
    oproduct.setProductQuantity(1);
    oproduct.setSku(product.getSku());
    // set order product price
    OrderProductPrice orderProductPrice = new OrderProductPrice();
    // default price (same as default product price)
    orderProductPrice.setDefaultPrice(true);
    orderProductPrice.setOrderProduct(oproduct);
    orderProductPrice.setProductPrice(dprice.getProductPriceAmount());
    orderProductPrice.setProductPriceCode(ProductPriceType.ONE_TIME.name());
    oproduct.getPrices().add(orderProductPrice);
    // order product attribute
    OrderProductAttribute orderProductAttribute = new OrderProductAttribute();
    orderProductAttribute.setOrderProduct(oproduct);
    // no extra charge
    orderProductAttribute.setProductAttributePrice(new BigDecimal("0.00"));
    orderProductAttribute.setProductAttributeName(whiteDescription.getName());
    orderProductAttribute.setProductOptionId(option.getId());
    orderProductAttribute.setProductOptionValueId(white.getId());
    oproduct.getOrderAttributes().add(orderProductAttribute);
    order.getOrderProducts().add(oproduct);
    /**
     * ORDER TOTAL *
     */
    OrderTotal subTotal = new OrderTotal();
    subTotal.setOrder(order);
    subTotal.setOrderTotalCode(Constants.OT_SUBTOTAL_MODULE_CODE);
    subTotal.setSortOrder(0);
    subTotal.setTitle("Sub Total");
    subTotal.setValue(dprice.getProductPriceAmount());
    order.getOrderTotal().add(subTotal);
    OrderTotal total = new OrderTotal();
    total.setOrder(order);
    total.setOrderTotalCode(Constants.OT_TOTAL_MODULE_CODE);
    total.setSortOrder(1);
    total.setTitle("Total");
    total.setValue(dprice.getProductPriceAmount());
    order.getOrderTotal().add(total);
    /**
     * ORDER HISTORY *
     */
    // create a log entry in order history
    OrderStatusHistory history = new OrderStatusHistory();
    history.setOrder(order);
    history.setDateAdded(new Date());
    history.setStatus(OrderStatus.ORDERED);
    history.setComments("We received your order");
    order.getOrderHistory().add(history);
    /**
     * CREATE ORDER *
     */
    orderService.create(order);
    /**
     * SEARCH ORDERS *
     */
    OrderCriteria criteria = new OrderCriteria();
    criteria.setStartIndex(0);
    criteria.setMaxCount(10);
    OrderList ordserList = orderService.listByStore(merchant, criteria);
    Assert.assertNotNull(ordserList);
    Assert.assertNotNull("Merchant Orders are null.", ordserList.getOrders());
    Assert.assertTrue("Merchant Orders count is not one.", (ordserList.getOrders() != null && ordserList.getOrders().size() == 1));
}
Also used : Category(com.salesmanager.core.model.catalog.category.Category) OrderProduct(com.salesmanager.core.model.order.orderproduct.OrderProduct) Customer(com.salesmanager.core.model.customer.Customer) OrderProduct(com.salesmanager.core.model.order.orderproduct.OrderProduct) Product(com.salesmanager.core.model.catalog.product.Product) ProductPrice(com.salesmanager.core.model.catalog.product.price.ProductPrice) OrderProductPrice(com.salesmanager.core.model.order.orderproduct.OrderProductPrice) ProductAttribute(com.salesmanager.core.model.catalog.product.attribute.ProductAttribute) OrderProductAttribute(com.salesmanager.core.model.order.orderproduct.OrderProductAttribute) ProductOptionDescription(com.salesmanager.core.model.catalog.product.attribute.ProductOptionDescription) ProductOptionValue(com.salesmanager.core.model.catalog.product.attribute.ProductOptionValue) Language(com.salesmanager.core.model.reference.language.Language) ProductAvailability(com.salesmanager.core.model.catalog.product.availability.ProductAvailability) Currency(com.salesmanager.core.model.reference.currency.Currency) Manufacturer(com.salesmanager.core.model.catalog.product.manufacturer.Manufacturer) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) ProductPriceDescription(com.salesmanager.core.model.catalog.product.price.ProductPriceDescription) HashSet(java.util.HashSet) ProductOption(com.salesmanager.core.model.catalog.product.attribute.ProductOption) Order(com.salesmanager.core.model.order.Order) Zone(com.salesmanager.core.model.reference.zone.Zone) ProductType(com.salesmanager.core.model.catalog.product.type.ProductType) OrderCriteria(com.salesmanager.core.model.order.OrderCriteria) Date(java.util.Date) BigDecimal(java.math.BigDecimal) CreditCard(com.salesmanager.core.model.order.payment.CreditCard) Billing(com.salesmanager.core.model.common.Billing) OrderProductPrice(com.salesmanager.core.model.order.orderproduct.OrderProductPrice) OrderProductAttribute(com.salesmanager.core.model.order.orderproduct.OrderProductAttribute) Country(com.salesmanager.core.model.reference.country.Country) ManufacturerDescription(com.salesmanager.core.model.catalog.product.manufacturer.ManufacturerDescription) CategoryDescription(com.salesmanager.core.model.catalog.category.CategoryDescription) Delivery(com.salesmanager.core.model.common.Delivery) ProductDescription(com.salesmanager.core.model.catalog.product.description.ProductDescription) OrderList(com.salesmanager.core.model.order.OrderList) OrderTotal(com.salesmanager.core.model.order.OrderTotal) OrderStatusHistory(com.salesmanager.core.model.order.orderstatus.OrderStatusHistory) ProductOptionValueDescription(com.salesmanager.core.model.catalog.product.attribute.ProductOptionValueDescription) Test(org.junit.Test)

Example 27 with Country

use of com.salesmanager.core.model.reference.country.Country in project shopizer by shopizer-ecommerce.

the class ReferencesTest method testReferences.

// @Test
@Ignore
public void testReferences() throws ServiceException {
    Language en = new Language();
    en.setCode("en");
    en.setSortOrder(0);
    languageService.save(en);
    Language fr = new Language();
    fr.setCode("fr");
    fr.setSortOrder(0);
    languageService.save(fr);
    List<Language> langs = languageService.getLanguages();
    System.out.println("Language size " + langs.size());
    Country us = new Country();
    us.setIsoCode("US");
    CountryDescription us_en = new CountryDescription();
    us_en.setLanguage(en);
    us_en.setCountry(us);
    us_en.setName("United States");
    us.getDescriptions().add(us_en);
    CountryDescription us_fr = new CountryDescription();
    us_fr.setLanguage(fr);
    us_fr.setCountry(us);
    us_fr.setName("Etats Unis");
    us.getDescriptions().add(us_fr);
    countryService.save(us);
    Country c = countryService.getByCode("US");
    System.out.println(c.getId());
    System.out.println("***********Done**************");
}
Also used : CountryDescription(com.salesmanager.core.model.reference.country.CountryDescription) Language(com.salesmanager.core.model.reference.language.Language) Country(com.salesmanager.core.model.reference.country.Country) Ignore(org.junit.Ignore)

Example 28 with Country

use of com.salesmanager.core.model.reference.country.Country in project shopizer by shopizer-ecommerce.

the class ShippingDistanceProcessorTest method testDistance.

@Ignore
public void testDistance() throws Exception {
    ShippingQuote shippingQuote = new ShippingQuote();
    Delivery delivery = new Delivery();
    delivery.setAddress("2055 Peel Street");
    delivery.setCity("Montreal");
    delivery.setPostalCode("H3A 1V4");
    Country country = new Country();
    country.setIsoCode("CA");
    country.setName("Canada");
    delivery.setCountry(country);
    Zone zone = new Zone();
    zone.setCode("QC");
    zone.setName("Quebec");
    delivery.setZone(zone);
    ShippingOrigin origin = new ShippingOrigin();
    origin.setAddress("7070, avenue Henri-Julien");
    origin.setCity("Montreal");
    origin.setPostalCode("H2S 3S3");
    origin.setZone(zone);
    origin.setCountry(country);
    // shippingDecisionTablePreProcessor.prePostProcessShippingQuotes(shippingQuote, null, null, delivery, origin, null, null, null, null, null, Locale.CANADA);
    System.out.println(delivery.getLatitude());
    System.out.println(delivery.getLongitude());
// System.out.println(shippingQuote.getQuoteInformations().get(Constants.DISTANCE_KEY));
}
Also used : ShippingQuote(com.salesmanager.core.model.shipping.ShippingQuote) Zone(com.salesmanager.core.model.reference.zone.Zone) Country(com.salesmanager.core.model.reference.country.Country) Delivery(com.salesmanager.core.model.common.Delivery) ShippingOrigin(com.salesmanager.core.model.shipping.ShippingOrigin) Ignore(org.junit.Ignore)

Example 29 with Country

use of com.salesmanager.core.model.reference.country.Country in project shopizer by shopizer-ecommerce.

the class TaxServiceImpl method calculateTax.

@Override
public List<TaxItem> calculateTax(OrderSummary orderSummary, Customer customer, MerchantStore store, Language language) throws ServiceException {
    if (customer == null) {
        return null;
    }
    List<ShoppingCartItem> items = orderSummary.getProducts();
    List<TaxItem> taxLines = new ArrayList<TaxItem>();
    if (items == null) {
        return taxLines;
    }
    // determine tax calculation basis
    TaxConfiguration taxConfiguration = this.getTaxConfiguration(store);
    if (taxConfiguration == null) {
        taxConfiguration = new TaxConfiguration();
        taxConfiguration.setTaxBasisCalculation(TaxBasisCalculation.SHIPPINGADDRESS);
    }
    Country country = customer.getBilling().getCountry();
    Zone zone = customer.getBilling().getZone();
    String stateProvince = customer.getBilling().getState();
    TaxBasisCalculation taxBasisCalculation = taxConfiguration.getTaxBasisCalculation();
    if (taxBasisCalculation.name().equals(TaxBasisCalculation.SHIPPINGADDRESS)) {
        Delivery shipping = customer.getDelivery();
        if (shipping != null) {
            country = shipping.getCountry();
            zone = shipping.getZone();
            stateProvince = shipping.getState();
        }
    } else if (taxBasisCalculation.name().equals(TaxBasisCalculation.BILLINGADDRESS)) {
        Billing billing = customer.getBilling();
        if (billing != null) {
            country = billing.getCountry();
            zone = billing.getZone();
            stateProvince = billing.getState();
        }
    } else if (taxBasisCalculation.name().equals(TaxBasisCalculation.STOREADDRESS)) {
        country = store.getCountry();
        zone = store.getZone();
        stateProvince = store.getStorestateprovince();
    }
    // do not collect tax on other provinces of same country
    if (!taxConfiguration.isCollectTaxIfDifferentProvinceOfStoreCountry()) {
        if ((zone != null && store.getZone() != null) && (zone.getId().longValue() != store.getZone().getId().longValue())) {
            return null;
        }
        if (!StringUtils.isBlank(stateProvince)) {
            if (store.getZone() != null) {
                if (!store.getZone().getName().equals(stateProvince)) {
                    return null;
                }
            } else if (!StringUtils.isBlank(store.getStorestateprovince())) {
                if (!store.getStorestateprovince().equals(stateProvince)) {
                    return null;
                }
            }
        }
    }
    // collect tax in different countries
    if (taxConfiguration.isCollectTaxIfDifferentCountryOfStoreCountry()) {
        // use store country
        country = store.getCountry();
        zone = store.getZone();
        stateProvince = store.getStorestateprovince();
    }
    if (zone == null && StringUtils.isBlank(stateProvince)) {
        return null;
    }
    Map<Long, TaxClass> taxClasses = new HashMap<Long, TaxClass>();
    // put items in a map by tax class id
    Map<Long, BigDecimal> taxClassAmountMap = new HashMap<Long, BigDecimal>();
    for (ShoppingCartItem item : items) {
        BigDecimal itemPrice = item.getItemPrice();
        TaxClass taxClass = item.getProduct().getTaxClass();
        int quantity = item.getQuantity();
        itemPrice = itemPrice.multiply(new BigDecimal(quantity));
        if (taxClass == null) {
            taxClass = taxClassService.getByCode(DEFAULT_TAX_CLASS);
        }
        BigDecimal subTotal = taxClassAmountMap.get(taxClass.getId());
        if (subTotal == null) {
            subTotal = new BigDecimal(0);
            subTotal.setScale(2, RoundingMode.HALF_UP);
        }
        subTotal = subTotal.add(itemPrice);
        taxClassAmountMap.put(taxClass.getId(), subTotal);
        taxClasses.put(taxClass.getId(), taxClass);
    }
    // tax on shipping ?
    // ShippingConfiguration shippingConfiguration = shippingService.getShippingConfiguration(store);
    /**
     * always calculate tax on shipping *
     */
    // if(shippingConfiguration!=null) {
    // if(shippingConfiguration.isTaxOnShipping()){
    // use default tax class for shipping
    TaxClass defaultTaxClass = taxClassService.getByCode(TaxClass.DEFAULT_TAX_CLASS);
    // taxClasses.put(defaultTaxClass.getId(), defaultTaxClass);
    BigDecimal amnt = taxClassAmountMap.get(defaultTaxClass.getId());
    if (amnt == null) {
        amnt = new BigDecimal(0);
        amnt.setScale(2, RoundingMode.HALF_UP);
    }
    ShippingSummary shippingSummary = orderSummary.getShippingSummary();
    if (shippingSummary != null && shippingSummary.getShipping() != null && shippingSummary.getShipping().doubleValue() > 0) {
        amnt = amnt.add(shippingSummary.getShipping());
        if (shippingSummary.getHandling() != null && shippingSummary.getHandling().doubleValue() > 0) {
            amnt = amnt.add(shippingSummary.getHandling());
        }
    }
    taxClassAmountMap.put(defaultTaxClass.getId(), amnt);
    // }
    // }
    List<TaxItem> taxItems = new ArrayList<TaxItem>();
    // iterate through the tax class and get appropriate rates
    for (Long taxClassId : taxClassAmountMap.keySet()) {
        // get taxRate by tax class
        List<TaxRate> taxRates = null;
        if (!StringUtils.isBlank(stateProvince) && zone == null) {
            taxRates = taxRateService.listByCountryStateProvinceAndTaxClass(country, stateProvince, taxClasses.get(taxClassId), store, language);
        } else {
            taxRates = taxRateService.listByCountryZoneAndTaxClass(country, zone, taxClasses.get(taxClassId), store, language);
        }
        if (taxRates == null || taxRates.size() == 0) {
            continue;
        }
        BigDecimal taxedItemValue = null;
        BigDecimal totalTaxedItemValue = new BigDecimal(0);
        totalTaxedItemValue.setScale(2, RoundingMode.HALF_UP);
        BigDecimal beforeTaxeAmount = taxClassAmountMap.get(taxClassId);
        for (TaxRate taxRate : taxRates) {
            // 5% ... 8% ...
            double taxRateDouble = taxRate.getTaxRate().doubleValue();
            if (taxRate.isPiggyback()) {
                // (compound)
                if (totalTaxedItemValue.doubleValue() > 0) {
                    beforeTaxeAmount = totalTaxedItemValue;
                }
            }
            // else just use nominal taxing (combine)
            double value = (beforeTaxeAmount.doubleValue() * taxRateDouble) / 100;
            double roundedValue = new BigDecimal(value).setScale(2, RoundingMode.HALF_UP).doubleValue();
            taxedItemValue = new BigDecimal(roundedValue).setScale(2, RoundingMode.HALF_UP);
            totalTaxedItemValue = beforeTaxeAmount.add(taxedItemValue);
            TaxItem taxItem = new TaxItem();
            taxItem.setItemPrice(taxedItemValue);
            taxItem.setLabel(taxRate.getDescriptions().get(0).getName());
            taxItem.setTaxRate(taxRate);
            taxItems.add(taxItem);
        }
    }
    Map<String, TaxItem> taxItemsMap = new TreeMap<String, TaxItem>();
    // consolidate tax rates of same code
    for (TaxItem taxItem : taxItems) {
        TaxRate taxRate = taxItem.getTaxRate();
        if (!taxItemsMap.containsKey(taxRate.getCode())) {
            taxItemsMap.put(taxRate.getCode(), taxItem);
        }
        TaxItem item = taxItemsMap.get(taxRate.getCode());
        BigDecimal amount = item.getItemPrice();
        amount = amount.add(taxItem.getItemPrice());
    }
    if (taxItemsMap.size() == 0) {
        return null;
    }
    @SuppressWarnings("rawtypes") Collection<TaxItem> values = taxItemsMap.values();
    @SuppressWarnings("unchecked") List<TaxItem> list = new ArrayList<TaxItem>(values);
    return list;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ShippingSummary(com.salesmanager.core.model.shipping.ShippingSummary) TaxRate(com.salesmanager.core.model.tax.taxrate.TaxRate) TaxConfiguration(com.salesmanager.core.model.tax.TaxConfiguration) Zone(com.salesmanager.core.model.reference.zone.Zone) TaxClass(com.salesmanager.core.model.tax.taxclass.TaxClass) TreeMap(java.util.TreeMap) BigDecimal(java.math.BigDecimal) TaxItem(com.salesmanager.core.model.tax.TaxItem) Billing(com.salesmanager.core.model.common.Billing) Country(com.salesmanager.core.model.reference.country.Country) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) TaxBasisCalculation(com.salesmanager.core.model.tax.TaxBasisCalculation) Delivery(com.salesmanager.core.model.common.Delivery)

Example 30 with Country

use of com.salesmanager.core.model.reference.country.Country in project shopizer by shopizer-ecommerce.

the class EmailTemplatesUtils method sendOrderEmail.

/**
 * Sends an email to the customer after a completed order
 * @param customer
 * @param order
 * @param customerLocale
 * @param language
 * @param merchantStore
 * @param contextPath
 */
@Async
public void sendOrderEmail(String toEmail, Customer customer, Order order, Locale customerLocale, Language language, MerchantStore merchantStore, String contextPath) {
    /**
     * issue with putting that elsewhere *
     */
    LOGGER.info("Sending welcome email to customer");
    try {
        Map<String, Zone> zones = zoneService.getZones(language);
        Map<String, Country> countries = countryService.getCountriesMap(language);
        // format Billing address
        StringBuilder billing = new StringBuilder();
        if (StringUtils.isBlank(order.getBilling().getCompany())) {
            billing.append(order.getBilling().getFirstName()).append(" ").append(order.getBilling().getLastName()).append(LINE_BREAK);
        } else {
            billing.append(order.getBilling().getCompany()).append(LINE_BREAK);
        }
        billing.append(order.getBilling().getAddress()).append(LINE_BREAK);
        billing.append(order.getBilling().getCity()).append(", ");
        if (order.getBilling().getZone() != null) {
            Zone zone = zones.get(order.getBilling().getZone().getCode());
            if (zone != null) {
                billing.append(zone.getName());
            }
            billing.append(LINE_BREAK);
        } else if (!StringUtils.isBlank(order.getBilling().getState())) {
            billing.append(order.getBilling().getState()).append(LINE_BREAK);
        }
        Country country = countries.get(order.getBilling().getCountry().getIsoCode());
        if (country != null) {
            billing.append(country.getName()).append(" ");
        }
        billing.append(order.getBilling().getPostalCode());
        // format shipping address
        StringBuilder shipping = null;
        if (order.getDelivery() != null && !StringUtils.isBlank(order.getDelivery().getFirstName())) {
            shipping = new StringBuilder();
            if (StringUtils.isBlank(order.getDelivery().getCompany())) {
                shipping.append(order.getDelivery().getFirstName()).append(" ").append(order.getDelivery().getLastName()).append(LINE_BREAK);
            } else {
                shipping.append(order.getDelivery().getCompany()).append(LINE_BREAK);
            }
            shipping.append(order.getDelivery().getAddress()).append(LINE_BREAK);
            shipping.append(order.getDelivery().getCity()).append(", ");
            if (order.getDelivery().getZone() != null) {
                Zone zone = zones.get(order.getDelivery().getZone().getCode());
                if (zone != null) {
                    shipping.append(zone.getName());
                }
                shipping.append(LINE_BREAK);
            } else if (!StringUtils.isBlank(order.getDelivery().getState())) {
                shipping.append(order.getDelivery().getState()).append(LINE_BREAK);
            }
            Country deliveryCountry = countries.get(order.getDelivery().getCountry().getIsoCode());
            if (country != null) {
                shipping.append(deliveryCountry.getName()).append(" ");
            }
            shipping.append(order.getDelivery().getPostalCode());
        }
        if (shipping == null && StringUtils.isNotBlank(order.getShippingModuleCode())) {
            // TODO IF HAS NO SHIPPING
            shipping = billing;
        }
        // format order
        // String storeUri = FilePathUtils.buildStoreUri(merchantStore, contextPath);
        StringBuilder orderTable = new StringBuilder();
        orderTable.append(TABLE);
        for (OrderProduct product : order.getOrderProducts()) {
            // Product productModel = productService.getByCode(product.getSku(), language);
            orderTable.append(TR);
            orderTable.append(TD).append(product.getProductName()).append(" - ").append(product.getSku()).append(CLOSING_TD);
            orderTable.append(TD).append(messages.getMessage("label.quantity", customerLocale)).append(": ").append(product.getProductQuantity()).append(CLOSING_TD);
            orderTable.append(TD).append(pricingService.getDisplayAmount(product.getOneTimeCharge(), merchantStore)).append(CLOSING_TD);
            orderTable.append(CLOSING_TR);
        }
        // order totals
        for (OrderTotal total : order.getOrderTotal()) {
            orderTable.append(TR_BORDER);
            // orderTable.append(TD);
            // orderTable.append(CLOSING_TD);
            orderTable.append(TD);
            orderTable.append(CLOSING_TD);
            orderTable.append(TD);
            orderTable.append("<strong>");
            if (total.getModule().equals("tax")) {
                orderTable.append(total.getText()).append(": ");
            } else {
                // if(total.getModule().equals("total") || total.getModule().equals("subtotal")) {
                // }
                orderTable.append(messages.getMessage(total.getOrderTotalCode(), customerLocale)).append(": ");
            // if(total.getModule().equals("total") || total.getModule().equals("subtotal")) {
            // }
            }
            orderTable.append("</strong>");
            orderTable.append(CLOSING_TD);
            orderTable.append(TD);
            orderTable.append("<strong>");
            orderTable.append(pricingService.getDisplayAmount(total.getValue(), merchantStore));
            orderTable.append("</strong>");
            orderTable.append(CLOSING_TD);
            orderTable.append(CLOSING_TR);
        }
        orderTable.append(CLOSING_TABLE);
        Map<String, String> templateTokens = emailUtils.createEmailObjectsMap(contextPath, merchantStore, messages, customerLocale);
        templateTokens.put(EmailConstants.LABEL_HI, messages.getMessage("label.generic.hi", customerLocale));
        templateTokens.put(EmailConstants.EMAIL_CUSTOMER_FIRSTNAME, order.getBilling().getFirstName());
        templateTokens.put(EmailConstants.EMAIL_CUSTOMER_LASTNAME, order.getBilling().getLastName());
        String[] params = { String.valueOf(order.getId()) };
        String[] dt = { DateUtil.formatDate(order.getDatePurchased()) };
        templateTokens.put(EmailConstants.EMAIL_ORDER_NUMBER, messages.getMessage("email.order.confirmation", params, customerLocale));
        templateTokens.put(EmailConstants.EMAIL_ORDER_DATE, messages.getMessage("email.order.ordered", dt, customerLocale));
        templateTokens.put(EmailConstants.EMAIL_ORDER_THANKS, messages.getMessage("email.order.thanks", customerLocale));
        templateTokens.put(EmailConstants.ADDRESS_BILLING, billing.toString());
        templateTokens.put(EmailConstants.ORDER_PRODUCTS_DETAILS, orderTable.toString());
        templateTokens.put(EmailConstants.EMAIL_ORDER_DETAILS_TITLE, messages.getMessage("label.order.details", customerLocale));
        templateTokens.put(EmailConstants.ADDRESS_BILLING_TITLE, messages.getMessage("label.customer.billinginformation", customerLocale));
        templateTokens.put(EmailConstants.PAYMENT_METHOD_TITLE, messages.getMessage("label.order.paymentmode", customerLocale));
        templateTokens.put(EmailConstants.PAYMENT_METHOD_DETAILS, messages.getMessage(new StringBuilder().append("payment.type.").append(order.getPaymentType().name()).toString(), customerLocale, order.getPaymentType().name()));
        if (StringUtils.isNotBlank(order.getShippingModuleCode())) {
            // templateTokens.put(EmailConstants.SHIPPING_METHOD_DETAILS, messages.getMessage(new StringBuilder().append("module.shipping.").append(order.getShippingModuleCode()).toString(),customerLocale,order.getShippingModuleCode()));
            templateTokens.put(EmailConstants.SHIPPING_METHOD_DETAILS, messages.getMessage(new StringBuilder().append("module.shipping.").append(order.getShippingModuleCode()).toString(), new String[] { merchantStore.getStorename() }, customerLocale));
            templateTokens.put(EmailConstants.ADDRESS_SHIPPING_TITLE, messages.getMessage("label.order.shippingmethod", customerLocale));
            templateTokens.put(EmailConstants.ADDRESS_DELIVERY_TITLE, messages.getMessage("label.customer.shippinginformation", customerLocale));
            templateTokens.put(EmailConstants.SHIPPING_METHOD_TITLE, messages.getMessage("label.customer.shippinginformation", customerLocale));
            templateTokens.put(EmailConstants.ADDRESS_DELIVERY, shipping.toString());
        } else {
            templateTokens.put(EmailConstants.SHIPPING_METHOD_DETAILS, "");
            templateTokens.put(EmailConstants.ADDRESS_SHIPPING_TITLE, "");
            templateTokens.put(EmailConstants.ADDRESS_DELIVERY_TITLE, "");
            templateTokens.put(EmailConstants.SHIPPING_METHOD_TITLE, "");
            templateTokens.put(EmailConstants.ADDRESS_DELIVERY, "");
        }
        String status = messages.getMessage("label.order." + order.getStatus().name(), customerLocale, order.getStatus().name());
        String[] statusMessage = { DateUtil.formatDate(order.getDatePurchased()), status };
        templateTokens.put(EmailConstants.ORDER_STATUS, messages.getMessage("email.order.status", statusMessage, customerLocale));
        String[] title = { merchantStore.getStorename(), String.valueOf(order.getId()) };
        Email email = new Email();
        email.setFrom(merchantStore.getStorename());
        email.setFromEmail(merchantStore.getStoreEmailAddress());
        email.setSubject(messages.getMessage("email.order.title", title, customerLocale));
        email.setTo(toEmail);
        email.setTemplateName(EmailConstants.EMAIL_ORDER_TPL);
        email.setTemplateTokens(templateTokens);
        LOGGER.debug("Sending email to {} for order id {} ", customer.getEmailAddress(), order.getId());
        emailService.sendHtmlEmail(merchantStore, email);
    } catch (Exception e) {
        LOGGER.error("Error occured while sending order confirmation email ", e);
    }
}
Also used : Email(com.salesmanager.core.business.modules.email.Email) OrderProduct(com.salesmanager.core.model.order.orderproduct.OrderProduct) Zone(com.salesmanager.core.model.reference.zone.Zone) Country(com.salesmanager.core.model.reference.country.Country) OrderTotal(com.salesmanager.core.model.order.OrderTotal) Async(org.springframework.scheduling.annotation.Async)

Aggregations

Country (com.salesmanager.core.model.reference.country.Country)33 Zone (com.salesmanager.core.model.reference.zone.Zone)21 Language (com.salesmanager.core.model.reference.language.Language)18 ArrayList (java.util.ArrayList)15 ServiceException (com.salesmanager.core.business.exception.ServiceException)14 MerchantStore (com.salesmanager.core.model.merchant.MerchantStore)11 Delivery (com.salesmanager.core.model.common.Delivery)10 ShippingQuote (com.salesmanager.core.model.shipping.ShippingQuote)9 BigDecimal (java.math.BigDecimal)8 List (java.util.List)7 ConversionException (com.salesmanager.core.business.exception.ConversionException)6 Billing (com.salesmanager.core.model.common.Billing)6 Customer (com.salesmanager.core.model.customer.Customer)6 ShippingOption (com.salesmanager.core.model.shipping.ShippingOption)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)6 PackageDetails (com.salesmanager.core.model.shipping.PackageDetails)5 ShippingConfiguration (com.salesmanager.core.model.shipping.ShippingConfiguration)5 ShippingOrigin (com.salesmanager.core.model.shipping.ShippingOrigin)5 IntegrationConfiguration (com.salesmanager.core.model.system.IntegrationConfiguration)5 Date (java.util.Date)5