DefaultJcrPlacedOrder.java 13.4 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.security.user.UserProperties
 *  com.day.cq.commons.LanguageUtil
 *  com.day.cq.personalization.UserPropertiesUtil
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Session
 *  javax.jcr.Workspace
 *  javax.jcr.query.Query
 *  javax.jcr.query.QueryManager
 *  javax.jcr.query.QueryResult
 *  org.apache.commons.collections.CollectionUtils
 *  org.apache.commons.collections.Predicate
 *  org.apache.jackrabbit.api.JackrabbitSession
 *  org.apache.jackrabbit.api.security.user.Authorizable
 *  org.apache.jackrabbit.api.security.user.UserManager
 *  org.apache.jackrabbit.util.ISO9075
 *  org.apache.jackrabbit.util.Text
 *  org.apache.sling.api.SlingHttpServletRequest
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ValueMap
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.commerce.common;

import com.adobe.cq.commerce.api.CommerceException;
import com.adobe.cq.commerce.api.CommerceSession;
import com.adobe.cq.commerce.api.PlacedOrder;
import com.adobe.cq.commerce.api.PriceInfo;
import com.adobe.cq.commerce.api.promotion.PromotionInfo;
import com.adobe.cq.commerce.api.promotion.VoucherInfo;
import com.adobe.cq.commerce.common.AbstractJcrCommerceSession;
import com.adobe.cq.commerce.impl.promotion.JcrVoucherImpl;
import com.adobe.granite.security.user.UserProperties;
import com.day.cq.commons.LanguageUtil;
import com.day.cq.personalization.UserPropertiesUtil;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Session;
import javax.jcr.Workspace;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.jackrabbit.util.ISO9075;
import org.apache.jackrabbit.util.Text;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultJcrPlacedOrder
implements PlacedOrder {
    protected static final Logger log = LoggerFactory.getLogger(AbstractJcrCommerceSession.class);
    protected Resource order;
    protected Map<String, Object> details;
    protected List<PriceInfo> prices;
    protected List<CommerceSession.CartEntry> entries;
    private AbstractJcrCommerceSession abstractJcrCommerceSession;

    public DefaultJcrPlacedOrder(AbstractJcrCommerceSession abstractJcrCommerceSession, String orderId) {
        this.abstractJcrCommerceSession = abstractJcrCommerceSession;
        this.order = this.getPlacedOrder(orderId);
    }

    @Override
    public String getOrderId() throws CommerceException {
        if (this.details == null) {
            this.lazyLoadOrderDetails();
        }
        return (String)this.details.get(this.abstractJcrCommerceSession.PN_ORDER_ID);
    }

    @Override
    public Map<String, Object> getOrder() throws CommerceException {
        if (this.details == null) {
            this.lazyLoadOrderDetails();
        }
        return this.details;
    }

    private void lazyLoadOrderDetails() throws CommerceException {
        this.details = new HashMap<String, Object>();
        if (this.order != null) {
            SimpleDateFormat dateFmt = new SimpleDateFormat("dd MMM, yyyy");
            this.details.put("orderPath", this.order.getPath());
            ValueMap orderProperties = this.order.getValueMap();
            for (Map.Entry entry : orderProperties.entrySet()) {
                String key = (String)entry.getKey();
                if ("cartItems".equals(key)) continue;
                Object property = entry.getValue();
                if (property instanceof Calendar) {
                    this.details.put(key, property);
                    this.details.put(key + "Formatted", dateFmt.format(((Calendar)property).getTime()));
                    continue;
                }
                this.details.put(key, property);
            }
            Resource orderDetailsChild = this.order.getChild("order-details");
            if (orderDetailsChild != null) {
                ValueMap orderDetailProperties = orderDetailsChild.getValueMap();
                for (Map.Entry detailProperty : orderDetailProperties.entrySet()) {
                    String key = (String)detailProperty.getKey();
                    Object property = detailProperty.getValue();
                    if (property instanceof Calendar) {
                        this.details.put(key, property);
                        this.details.put(key + "Formatted", dateFmt.format(((Calendar)property).getTime()));
                        continue;
                    }
                    this.details.put(key, property);
                }
            }
            this.details.put("orderStatus", this.abstractJcrCommerceSession.getOrderStatus((String)this.details.get(this.abstractJcrCommerceSession.PN_ORDER_ID)));
        }
    }

    @Override
    public List<PriceInfo> getCartPriceInfo(Predicate filter) throws CommerceException {
        if (this.prices == null) {
            this.lazyLoadPriceInfo();
        }
        ArrayList<PriceInfo> filteredPrices = new ArrayList<PriceInfo>();
        CollectionUtils.select(this.prices, (Predicate)filter, filteredPrices);
        return filteredPrices;
    }

    @Override
    public String getCartPrice(Predicate filter) throws CommerceException {
        PriceInfo price;
        if (this.prices == null) {
            this.lazyLoadPriceInfo();
        }
        if ((price = (PriceInfo)((Object)CollectionUtils.find(this.prices, (Predicate)filter))) != null) {
            return price.getFormattedString();
        }
        return "";
    }

    protected void lazyLoadPriceInfo() throws CommerceException {
        this.prices = new ArrayList<PriceInfo>();
        if (this.order != null) {
            ValueMap orderMap = this.order.getValueMap();
            String languageTag = (String)orderMap.get("jcr:language", String.class);
            Locale locale = languageTag != null ? LanguageUtil.getLocale((String)languageTag) : this.abstractJcrCommerceSession.getLocale();
            String currencyCode = (String)orderMap.get("currencyCode", String.class);
            if (!currencyCode.equals(Currency.getInstance(locale).getCurrencyCode())) {
                log.error("Currency for locale has changed since order was saved.  Unable to load prices.");
                return;
            }
            PriceInfo price = new PriceInfo((BigDecimal)orderMap.get("orderTotalPrice", BigDecimal.class), locale);
            price.put("com.adobe.cq.commerce.common.PriceFilter.types", new HashSet<String>(Arrays.asList("ORDER", "TOTAL", currencyCode)));
            this.prices.add(price);
            price = new PriceInfo((BigDecimal)orderMap.get("orderTotalTax", BigDecimal.class), locale);
            price.put("com.adobe.cq.commerce.common.PriceFilter.types", new HashSet<String>(Arrays.asList("ORDER", "TAX", currencyCode)));
            this.prices.add(price);
            price = new PriceInfo((BigDecimal)orderMap.get("cartSubtotal", BigDecimal.class), locale);
            price.put("com.adobe.cq.commerce.common.PriceFilter.types", new HashSet<String>(Arrays.asList("CART", "PRE_TAX", currencyCode)));
            this.prices.add(price);
            price = new PriceInfo((BigDecimal)orderMap.get("orderShipping", BigDecimal.class), locale);
            price.put("com.adobe.cq.commerce.common.PriceFilter.types", new HashSet<String>(Arrays.asList("SHIPPING", currencyCode)));
            this.prices.add(price);
        }
    }

    @Override
    public List<CommerceSession.CartEntry> getCartEntries() throws CommerceException {
        if (this.entries == null) {
            this.lazyLoadCartEntries();
        }
        return this.entries;
    }

    protected void lazyLoadCartEntries() throws CommerceException {
        this.entries = new ArrayList<CommerceSession.CartEntry>();
        if (this.order != null) {
            String[] serializedEntries;
            for (String serializedEntry : serializedEntries = (String[])this.order.getValueMap().get("cartItems", String[].class)) {
                try {
                    CommerceSession.CartEntry entry = this.abstractJcrCommerceSession.deserializeCartEntry(serializedEntry, this.entries.size());
                    this.entries.add(entry);
                    continue;
                }
                catch (Exception e) {
                    log.error("Unable to load product from order: {}", (Object)serializedEntry);
                }
            }
        }
    }

    @Override
    public List<PromotionInfo> getPromotions() throws CommerceException {
        ArrayList<PromotionInfo> infos = new ArrayList<PromotionInfo>();
        if (this.order != null) {
            String[] records;
            for (String record : records = (String[])this.order.getValueMap().get("promotions", (Object)new String[0])) {
                try {
                    String[] fields = record.split(";", 3);
                    String path = "null".equals(fields[0]) ? null : fields[0];
                    Integer entryIndex = "null".equals(fields[1]) ? null : Integer.valueOf(Integer.parseInt(fields[1]));
                    String message = "null".equals(fields[2]) ? null : fields[2];
                    infos.add(new PromotionInfo(path, "", PromotionInfo.PromotionStatus.FIRED, "", message, entryIndex));
                    continue;
                }
                catch (Exception e) {
                    log.error("Unable to load promotion from order: {}", (Object)record);
                }
            }
        }
        return infos;
    }

    @Override
    public List<VoucherInfo> getVoucherInfos() throws CommerceException {
        ArrayList<VoucherInfo> infos = new ArrayList<VoucherInfo>();
        if (this.order != null) {
            String[] records;
            for (String record : records = (String[])this.order.getValueMap().get("vouchers", (Object)new String[0])) {
                String[] fields = record.split(";", 3);
                try {
                    if (fields.length == 1) {
                        String path = fields[0];
                        JcrVoucherImpl voucher = new JcrVoucherImpl(this.order.getResourceResolver().getResource(path));
                        infos.add(new VoucherInfo(voucher.getCode(), voucher.getPath(), "", "", true, ""));
                        continue;
                    }
                    String code = fields[0].equals("null") ? null : fields[0];
                    String path = fields[1].equals("null") ? null : fields[1];
                    String message = fields[2].equals("null") ? null : fields[2];
                    infos.add(new VoucherInfo(code, path, "", "", true, message));
                    continue;
                }
                catch (Exception e) {
                    log.error("Unable to load voucher from order: {}", (Object)record);
                }
            }
        }
        return infos;
    }

    protected Resource getPlacedOrder(String orderId) {
        try {
            Session userSession = (Session)this.abstractJcrCommerceSession.resolver.adaptTo(Session.class);
            UserProperties userProperties = (UserProperties)this.abstractJcrCommerceSession.request.adaptTo(UserProperties.class);
            if (userProperties != null && !UserPropertiesUtil.isAnonymous((UserProperties)userProperties)) {
                UserManager um = ((JackrabbitSession)userSession).getUserManager();
                Authorizable user = um.getAuthorizable(userProperties.getAuthorizableID());
                if (orderId.startsWith("/")) {
                    Resource orderResource = this.abstractJcrCommerceSession.resolver.getResource(orderId);
                    if (orderResource != null && orderId.startsWith(user.getPath() + "/commerce/orders/")) {
                        return orderResource;
                    }
                    return null;
                }
                StringBuilder buffer = new StringBuilder();
                buffer.append("/jcr:root").append(ISO9075.encodePath((String)(user.getPath() + "/commerce/orders/"))).append("/element(*)[@orderId = '").append(Text.escapeIllegalXpathSearchChars((String)orderId).replaceAll("'", "''")).append("']");
                Query query = userSession.getWorkspace().getQueryManager().createQuery(buffer.toString(), "xpath");
                NodeIterator nodeIterator = query.execute().getNodes();
                if (nodeIterator.hasNext()) {
                    return this.abstractJcrCommerceSession.resolver.getResource(nodeIterator.nextNode().getPath());
                }
            }
        }
        catch (Exception e) {
            log.error("Error while searching for order history with orderId '" + orderId + "'", (Throwable)e);
        }
        return null;
    }
}