VendorJcrPlacedOrder.java 14.5 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.commons.jcr.JcrUtil
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  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.util.Text
 *  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.Product;
import com.adobe.cq.commerce.api.promotion.PromotionInfo;
import com.adobe.cq.commerce.api.promotion.VoucherInfo;
import com.adobe.cq.commerce.common.AbstractJcrCommerceService;
import com.adobe.cq.commerce.common.DefaultJcrCartEntry;
import com.adobe.cq.commerce.impl.promotion.JcrVoucherImpl;
import com.day.cq.commons.jcr.JcrUtil;
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.Property;
import javax.jcr.RepositoryException;
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.util.Text;
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 VendorJcrPlacedOrder
implements PlacedOrder {
    protected static final Logger log = LoggerFactory.getLogger(VendorJcrPlacedOrder.class);
    protected Resource order;
    protected Map<String, Object> details;
    protected List<PriceInfo> prices;
    protected List<CommerceSession.CartEntry> entries;
    protected AbstractJcrCommerceService commerceService;
    protected Locale locale;

    public VendorJcrPlacedOrder(AbstractJcrCommerceService commerceService, String orderId, Locale locale) {
        this.commerceService = commerceService;
        this.locale = locale;
        this.order = this.getPlacedOrder(orderId);
    }

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

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

    public void updateOrder(Map<String, Object> delta, boolean autoSave) throws CommerceException {
        try {
            Node orderNode = (Node)this.order.adaptTo(Node.class);
            for (Map.Entry<String, Object> entry : delta.entrySet()) {
                String key = entry.getKey();
                if ("orderPath".equals(key) || key.endsWith("Formatted")) continue;
                this.setProperty(orderNode, key, entry.getValue());
            }
            if (autoSave) {
                orderNode.getSession().save();
            }
        }
        catch (RepositoryException e) {
            throw new CommerceException("Failed to persist the order properties", (Throwable)e);
        }
        finally {
            this.details = null;
            this.prices = null;
            this.entries = null;
        }
    }

    protected void setProperty(Node node, String propertyPath, Object value) throws RepositoryException {
        String propertyName = propertyPath;
        int lastSlash = propertyPath.lastIndexOf(47);
        if (lastSlash >= 0) {
            node = JcrUtil.createPath((Node)node, (String)propertyPath.substring(0, lastSlash), (boolean)false, (String)"nt:unstructured", (String)"nt:unstructured", (Session)node.getSession(), (boolean)false);
            propertyName = propertyPath.substring(lastSlash + 1);
        }
        if (value instanceof Calendar) {
            node.setProperty(propertyName, (Calendar)value);
        } else if (value instanceof BigDecimal) {
            node.setProperty(propertyName, (BigDecimal)value);
        } else if (value instanceof String) {
            String stringValue = (String)value;
            if (stringValue.startsWith("[") && stringValue.endsWith("]")) {
                String[] stringValues = stringValue.substring(1, stringValue.length() - 1).split(",");
                node.setProperty(propertyName, stringValues);
            } else {
                node.setProperty(propertyName, stringValue);
            }
        } else if (value instanceof String[]) {
            node.setProperty(propertyName, (String[])value);
        }
    }

    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("order-details/" + key, property);
                        this.details.put("order-details/" + key + "Formatted", dateFmt.format(((Calendar)property).getTime()));
                        continue;
                    }
                    this.details.put("order-details/" + key, property);
                }
            }
        }
    }

    @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 currencyCode = (String)orderMap.get("currencyCode", String.class);
            if (currencyCode == null) {
                log.error("Missing currencyCode in order: " + this.order.getPath());
                log.error("Assuming 'USD'");
                currencyCode = "USD";
            }
            Currency currency = Currency.getInstance(currencyCode);
            PriceInfo price = new PriceInfo((BigDecimal)orderMap.get("orderTotalPrice", BigDecimal.class), this.locale, currency);
            price.put("com.adobe.cq.commerce.common.PriceFilter.types", new HashSet<String>(Arrays.asList("orderTotalPrice")));
            this.prices.add(price);
            price = new PriceInfo((BigDecimal)orderMap.get("orderTotalTax", BigDecimal.class), this.locale, currency);
            price.put("com.adobe.cq.commerce.common.PriceFilter.types", new HashSet<String>(Arrays.asList("orderTotalTax")));
            this.prices.add(price);
            price = new PriceInfo((BigDecimal)orderMap.get("cartSubtotal", BigDecimal.class), this.locale, currency);
            price.put("com.adobe.cq.commerce.common.PriceFilter.types", new HashSet<String>(Arrays.asList("cartSubtotal")));
            this.prices.add(price);
            price = new PriceInfo((BigDecimal)orderMap.get("orderShipping", BigDecimal.class), this.locale, currency);
            price.put("com.adobe.cq.commerce.common.PriceFilter.types", new HashSet<String>(Arrays.asList("orderShipping")));
            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", (Object)new String[0])) {
                try {
                    CommerceSession.CartEntry entry = this.deserializeCartEntry(serializedEntry, this.entries.size());
                    this.entries.add(entry);
                    continue;
                }
                catch (Exception e) {
                    log.error("Unable to load product from order: {}", (Object)serializedEntry);
                }
            }
        }
    }

    protected CommerceSession.CartEntry deserializeCartEntry(String str, int index) throws CommerceException {
        Object[] entryData = this.commerceService.deserializeCartEntryData(str);
        Product product = (Product)entryData[0];
        int quantity = (Integer)entryData[1];
        DefaultJcrCartEntry entry = this.commerceService.newCartEntryImpl(index, product, quantity);
        if (entryData[2] == null) {
            return entry;
        }
        Map properties = (Map)entryData[2];
        entry.updateProperties(properties);
        return entry;
    }

    @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: " + record, (Throwable)e);
                }
            }
        }
        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 = "null".equals(fields[0]) ? null : fields[0];
                    String path = "null".equals(fields[1]) ? null : fields[1];
                    String message = "null".equals(fields[2]) ? 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 {
            if (orderId.startsWith("/")) {
                return this.commerceService.resolver.getResource(orderId);
            }
            StringBuilder buffer = new StringBuilder();
            buffer.append("/jcr:root/etc/commerce/orders/element(*)[@orderId = '").append(Text.escapeIllegalXpathSearchChars((String)orderId).replaceAll("'", "''")).append("']");
            QueryManager queryManager = ((Session)this.commerceService.resolver.adaptTo(Session.class)).getWorkspace().getQueryManager();
            Query query = queryManager.createQuery(buffer.toString(), "xpath");
            NodeIterator nodeIterator = query.execute().getNodes();
            if (nodeIterator.hasNext()) {
                return this.commerceService.resolver.getResource(nodeIterator.nextNode().getPath());
            }
        }
        catch (Exception e) {
            log.error("Error while searching for order history with orderId '" + orderId + "'", (Throwable)e);
        }
        return null;
    }
}