⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 checkoutevents.java

📁 国外的一套开源CRM
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
            }
            Iterator npi = nullPaymentIds.iterator();
            while (npi.hasNext()) {
                String paymentMethodId = (String) npi.next();
                double requiredAmount = cart.getGrandTotal() - cart.getBillingAccountAmount();
                double selectedPaymentTotal = cart.getSelectedPaymentMethodsTotal();
                double nullAmount = requiredAmount - selectedPaymentTotal;
                if (nullAmount > 0) {
                    cart.setPaymentMethodAmount(paymentMethodId, new Double(nullAmount));
                }
            }
        }

        // verify the selected payment method amounts will cover the total
        double requiredAmount = cart.getGrandTotal() - cart.getBillingAccountAmount();
        double selectedPaymentTotal = cart.getSelectedPaymentMethodsTotal();
        if (paymentMethods != null && paymentMethods.size() > 0 && requiredAmount > selectedPaymentTotal) {
            Debug.logError("Required Amount : " + requiredAmount + " / Selected Amount : " + selectedPaymentTotal, module);
            errMsg = UtilProperties.getMessage(resource,"checkevents.payment_not_cover_this_order", (cart != null ? cart.getLocale() : Locale.getDefault()));
            request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg );
            return "error";
        }

        return "success";
    }

    public static Map getSelectedPaymentMethods(HttpServletRequest request) {
        ShoppingCart cart = (ShoppingCart) request.getSession().getAttribute("shoppingCart");
        Locale locale = UtilHttp.getLocale(request);
        String currencyFormat = UtilProperties.getPropertyValue("general.properties", "currency.decimal.format", "##0.00");
        DecimalFormat formatter = new DecimalFormat(currencyFormat);
        Map selectedPaymentMethods = new HashMap();
        String[] paymentMethods = request.getParameterValues("checkOutPaymentId");
        String errMsg = null;

        if (paymentMethods != null) {
            for (int i = 0; i < paymentMethods.length; i++) {
                String amountStr = request.getParameter("amount_" + paymentMethods[i]);
                Double amount = null;
                if (amountStr != null && amountStr.length() > 0 && !"REMAINING".equals(amountStr)) {
                    try {
                        amount = new Double(formatter.parse(amountStr).doubleValue());
                    } catch (ParseException e) {
                        Debug.logError(e, module);
                        errMsg = UtilProperties.getMessage(resource,"checkevents.invalid_amount_set_for_payment_method", (cart != null ? cart.getLocale() : Locale.getDefault()));
                        request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg );
                        return null;
                    }
                }
                selectedPaymentMethods.put(paymentMethods[i], amount);
            }
        }
        Debug.logInfo("Selected Payment Methods : " + selectedPaymentMethods, module);
        return selectedPaymentMethods;
    }

    private static void validateGiftCardAmounts(HttpServletRequest request) {
        ShoppingCart cart = (ShoppingCart) request.getSession().getAttribute("shoppingCart");
        GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
        LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");

        // get the product store
        GenericValue productStore = ProductStoreWorker.getProductStore(cart.getProductStoreId(), delegator);
        if (productStore != null && "N".equalsIgnoreCase(productStore.getString("checkGcBalance"))) {
            return;
        }

        // get the payment config
        String paymentConfig = ProductStoreWorker.getProductStorePaymentProperties(delegator, cart.getProductStoreId(), "GIFT_CARD", null, true);

        // get the gift card objects to check
        Iterator i = cart.getGiftCards().iterator();
        while (i.hasNext()) {
            GenericValue gc = (GenericValue) i.next();
            Map gcBalanceMap = null;
            double gcBalance = 0.00;
            try {
                Map ctx = UtilMisc.toMap("paymentConfig", paymentConfig);
                ctx.put("currency", cart.getCurrency());
                ctx.put("cardNumber", gc.getString("cardNumber"));
                ctx.put("pin", gc.getString("pinNumber"));                
                gcBalanceMap = dispatcher.runSync("balanceInquireGiftCard", ctx);
            } catch (GenericServiceException e) {
                Debug.logError(e, module);
            }
            if (gcBalanceMap != null) {
                Double bal = (Double) gcBalanceMap.get("balance");
                if (bal != null) {
                    gcBalance = bal.doubleValue();
                }
            }

            // get the bill-up to amount
            Double billUpTo = cart.getPaymentMethodAmount(gc.getString("paymentMethodId"));

            // null bill-up to means use the full balance || update the bill-up to with the balance
            if (billUpTo == null || billUpTo.doubleValue() == 0 || gcBalance < billUpTo.doubleValue()) {
                cart.setPaymentMethodAmount(gc.getString("paymentMethodId"), new Double(gcBalance));
            }                        
        }
    }

    public static String setCheckOutOptions(HttpServletRequest request, HttpServletResponse response) {
        ShoppingCart cart = (ShoppingCart) request.getSession().getAttribute("shoppingCart");
        LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
        GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");

        String errMsg = null;

        // get the currency format
        String currencyFormat = UtilProperties.getPropertyValue("general.properties", "currency.decimal.format", "##0.00");
        DecimalFormat formatter = new DecimalFormat(currencyFormat);

        // Set the payment options
        Map selectedPaymentMethods = getSelectedPaymentMethods(request);
        if (selectedPaymentMethods == null) {
            return "error";
        }

        String shippingMethod = request.getParameter("shipping_method");
        String shippingContactMechId = request.getParameter("shipping_contact_mech_id");
        String correspondingPoId = request.getParameter("corresponding_po_id");
        String shippingInstructions = request.getParameter("shipping_instructions");
        String orderAdditionalEmails = request.getParameter("order_additional_emails");
        String maySplit = request.getParameter("may_split");
        String giftMessage = request.getParameter("gift_message");
        String isGift = request.getParameter("is_gift");
        List singleUsePayments = new ArrayList();

        // get the billing account and amount
        String billingAccountId = request.getParameter("billingAccountId");
        String billingAcctAmtStr = request.getParameter("amount_" + billingAccountId);
        Double billingAccountAmt = null;
        // parse the amount to a decimal
        if (billingAcctAmtStr != null) {
            try {
                billingAccountAmt = new Double(formatter.parse(billingAcctAmtStr).doubleValue());
            } catch (ParseException e) {
                Debug.logError(e, module);
                Map messageMap = UtilMisc.toMap("billingAccountId", billingAccountId );
                errMsg = UtilProperties.getMessage(resource,"checkevents.invalid_amount_set_for_billing_account", messageMap, (cart != null ? cart.getLocale() : Locale.getDefault()));
                request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg );
//                request.setAttribute("_ERROR_MESSAGE_", "<li>Invalid amount set for Billing Account #" + billingAccountId);
                return "error";
            }
        }

        // get a request map of parameters
        Map params = UtilHttp.getParameterMap(request);
        CheckOutHelper checkOutHelper = new CheckOutHelper(dispatcher, delegator, cart);

        // check for gift card not on file
        Map gcResult = checkOutHelper.checkGiftCard(params, selectedPaymentMethods);
        ServiceUtil.getMessages(request, gcResult, null, "<li>", "</li>", "<ul>", "</ul>", null, null);
        if (gcResult.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR)) {
            return "error";
        } else {
            String gcPaymentMethodId = (String) gcResult.get("paymentMethodId");
            Double gcAmount = (Double) gcResult.get("amount");
            if (gcPaymentMethodId != null) {
                selectedPaymentMethods.put(gcPaymentMethodId, gcAmount);
                if ("Y".equalsIgnoreCase(request.getParameter("singleUseGiftCard"))) {
                    singleUsePayments.add(gcPaymentMethodId);
                }
            }
        }

        Map optResult = checkOutHelper.setCheckOutOptions(shippingMethod, shippingContactMechId, selectedPaymentMethods,
            singleUsePayments, billingAccountId, billingAccountAmt, correspondingPoId, shippingInstructions,
            orderAdditionalEmails, maySplit, giftMessage, isGift);

       ServiceUtil.getMessages(request, optResult, null, "<li>", "</li>", "<ul>", "</ul>", null, null);
        if (optResult.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR)) {
            return "error";
        } else {
            return "success";
        }
    }

    // Create order event - uses createOrder service for processing
    public static String createOrder(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        ServletContext application = ((ServletContext) request.getAttribute("servletContext"));
        ShoppingCart cart = ShoppingCartEvents.getCartObject(request);
        LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
        GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
        GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
        CheckOutHelper checkOutHelper = new CheckOutHelper(dispatcher, delegator, cart);
        Map callResult;

        // remove this whenever creating an order so quick reorder cache will refresh/recalc
        session.removeAttribute("_QUICK_REORDER_PRODUCTS_");

        boolean areOrderItemsExploded = explodeOrderItems(delegator, cart);

        //get the TrackingCodeOrder List
        List trackingCodeOrders = TrackingCodeEvents.makeTrackingCodeOrders(request);
        String distributorId = (String) session.getAttribute("_DISTRIBUTOR_ID_");
        String affiliateId = (String) session.getAttribute("_AFFILIATE_ID_");
        String visitId = VisitHandler.getVisitId(session);
        String webSiteId = CatalogWorker.getWebSiteId(request);

        callResult = checkOutHelper.createOrder(userLogin, distributorId, affiliateId, trackingCodeOrders, areOrderItemsExploded,
            visitId, webSiteId);

        if (callResult != null) {
            ServiceUtil.getMessages(request, callResult, null, "<li>", "</li>", "<ul>", "</ul>", null, null);

            if (callResult.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_SUCCESS)) {
                // set the orderId for use by chained events
                String orderId = cart.getOrderId();
                request.setAttribute("order_id", orderId);
                request.setAttribute("orderId", orderId);
                request.setAttribute("orderAdditionalEmails", cart.getOrderAdditionalEmails());
            }
        }

        return cart.getOrderType().toLowerCase();
    }

    // Event wrapper for the tax calc.
    public static String calcTax(HttpServletRequest request, HttpServletResponse response) {
        try {
            calcTax(request);
        } catch (GeneralException e) {
            request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
            return "error";
        }
        return "success";
    }

    // Invoke the taxCalc
    private static void calcTax(HttpServletRequest request) throws GeneralException {
        LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
        GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
        ShoppingCart cart = (ShoppingCart) request.getSession().getAttribute("shoppingCart");
        CheckOutHelper checkOutHelper = new CheckOutHelper(dispatcher, delegator, cart);

        //Calculate and add the tax adjustments
        checkOutHelper.calcAndAddTax();
    }

    public static boolean explodeOrderItems(GenericDelegator delegator, ShoppingCart cart) {
        if (cart == null) return false;
        GenericValue productStore = ProductStoreWorker.getProductStore(cart.getProductStoreId(), delegator);
        if (productStore == null || productStore.get("explodeOrderItems") == null) {
                return false;
        }
        return productStore.getBoolean("explodeOrderItems").booleanValue();
    }

    // Event wrapper for processPayment.
    public static String processPayment(HttpServletRequest request, HttpServletResponse response) {
        // run the process payment process + approve order when complete; may also run sync fulfillments
        int failureCode = 0;
        try {
            if (!processPayment(request)) {
                failureCode = 1;
            }
        } catch (GeneralException e) {
            Debug.logError(e, module);
            ServiceUtil.setMessages(request, "<li>" + e.getMessage() + "</li>", null, null);
            failureCode = 2;
        } catch (GeneralRuntimeException e) {
            Debug.logError(e, module);
            ServiceUtil.setMessages(request, "<li>" + e.getMessage() + "</li>", null, null);
        }

        // event return based on failureCode
        switch (failureCode) {
            case 0:
                return "success";
            case 1:
                return "fail";
            default:
                return "error";
        }
    }

    private static boolean processPayment(HttpServletRequest request) throws GeneralException {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -