문제

저는 고객이 고객이 거기에있는 품목을 기반으로 바구니에 적용되는 자동 할인 코드를 얻을 수있는 프로젝트에서 작업 해 왔습니다.

이렇게 된 코드 로직으로 이것이 완벽하게 일하고 있다고 생각했습니다. 나는 코드가 생성되면 (백엔드에서)을보고 있었고, 장바구니에 할인을 보였습니다. 그러나 오늘날 고객 신용은 주문 비용을 지불하는 데 전적으로 사용될 수 없다는 것이 제기되었습니다.

이 모듈로 성공적으로 좁혀졌습니다. 비활성화 할 때 문제가 없습니다. 그러나 믿음은 우리가 파리에 코드를 생성하고 Magento가 실제 할인을 처리하는 것이 정상적으로 작동해야합니다. 디버깅은 무료 체크 아웃에서 사용할 수 있는지 확인할 때 그랜드 합계가 원래 가격이 아직 원래 가격임을 보여줍니다.

이 작업을 호환 할 수 있도록 입력 해야하는 추가 로직이 있습니까?

클라이언트 기밀성 이유로 인해 클라이언트 기밀성 이유로 인해 마스크 된 네임 스페이스 / 모듈 이름이 약간 마스크 된 이름을 알고 있으므로 코드가 실행되고 내가 예상 한 것을 실행하는 것과 같은 무시하십시오.

기대 :

고객이 할인 코드 할인 기준을 충족하는 경우 장바구니에 대한 할인을 얻습니다.

고객이 충분히 지불 할 충분한 상점 크레딧이있는 경우 상점 크레딧으로 가득 차 있어야합니다.

실제 :

할인 코드가 생성됩니다 (해당되는 경우)

고객은 상점 크레딧을 사용하여 구매에 충분히 지불 할 수 없습니다.

옵저버 : CHECKOUT_CART_PRODUCT_ADD_AFTER

public function checkout_cart_product_add_after($observer)
{
    if (!Mage::helper('core')->isModuleOutputEnabled('Namespace_WholesaleDiscount')) {
        return;
    }

    /*
     * When emptying the cart this observer is updated
     * due to the setting of it to 0 for deletion.
     * This prevents running the observer and thus resetting items in quote.
     */
    $request = Mage::app()->getRequest()->getParam('update_cart_action');
    if ($request == 'empty_cart') {
        return;
    }



    try {
        $model = Mage::getModel('salesrule/rule')
            ->getCollection()
            ->addFieldToSelect('*')
            ->addFieldToFilter('name', array('eq' => sprintf('WHOLESALE AUTO_%s', Mage::getSingleton('customer/session')->getSessionId())))
            ->load();

        if ($model->count() < 1) {
            // No coupon yet.
            $helper = Mage::helper('wholesalediscount');
            $helper->createDiscountCode($helper->getDiscountAmount(), Mage::getSingleton('customer/session')->getSessionId());

            $model = Mage::getModel('salesrule/rule')
                ->getCollection()
                ->addFieldToFilter('name', array('eq' => sprintf('WHOLESALE AUTO_%s', Mage::getSingleton('customer/session')->getSessionId())))
                ->getFirstItem();

        } else {
            $helper = Mage::helper('wholesalediscount');

            $model = $model->getFirstItem();


            $model->setDiscountAmount($helper->getDiscountAmount());
            $code = Mage::helper('core')->getRandomString(16);

            // Magento initializes the coupon_code, but on model load it is code.
            $model->setCouponCode($code);
            $model->setCode($code);

            $model->save();
        }

        $couponCode = $model->getCode();
        /* END This part is my extra, just to load our coupon for this specific customer */

        Mage::getSingleton('checkout/cart')
            ->getQuote()
            ->getShippingAddress()
            ->setCollectShippingRates(true);

        Mage::getSingleton('checkout/cart')
            ->getQuote()
            ->setCouponCode(strlen($couponCode) ? $couponCode : '')
            ->collectTotals()
            ->save();

    } catch (Exception $e) {
        Mage::logException($e);
    }

    return $this;
}
.

도우미 논리 : 위와 같이 나는 잠재적으로 비즈니스 논리를 잠재적으로 드러내거나 클라이언트 기밀성을 위반하는 것을 가리 킵니다. 이전과 마찬가지로 두 가지 방법은 여기에 두 가지 방법을 단순히 할인 코드 쿠폰을 생성하고 (관리자에서 일할 수 있으며 할인을 적용 할 수 있으며 할인을 적용 할 수 있습니다) 할인 (이것은 완전히 사업 논리)

을 계산합니다.
public function createDiscountCode($discount, $reference)
    {
        $now = new Zend_Date();
        $now->setTimezone('UTC');
        $data = array(
            'product_ids' => null,
            'name' => sprintf('WHOLESALE AUTO_%s', $reference),
            'description' => null,
            'is_active' => 1,
            'website_ids' => array(Mage::app()->getWebsite()->getId()),
            'customer_group_ids' => array(Mage::getSingleton('customer/session')->getCustomerGroupId()),
            'coupon_type' => 2,
            'coupon_code' => Mage::helper('core')->getRandomString(16),
            'uses_per_coupon' => 1,
            'uses_per_customer' => 1,
            'from_date' => $now->getFullYear() . "-". $now->getMonth() . "-" . $now->getDay(),
            'to_date' => null,
            'sort_order' => null,
            'is_rss' => 1,
            'rule' => array(
                'conditions' => array(
                    array(
                        'type' => 'salesrule/rule_condition_combine',
                        'aggregator' => 'all',
                        'value' => 1,
                        'new_child' => null
                    )
                )
            ),
            'simple_action' => 'cart_fixed',
            'discount_amount' => $this->getDiscountAmount(),
            'discount_qty' => 0,
            'discount_step' => null,
            'apply_to_shipping' => 0,
            'simple_free_shipping' => 0,
            'stop_rules_processing' => 0,
            'rule' => array(
                'actions' => array(
                    array(
                        'type' => 'salesrule/rule_condition_product_combine',
                        'aggregator' => 'all',
                        'value' => 1,
                        'new_child' => null
                    )
                )
            ),
            'store_labels' => array('E-Liquids With Kits')
        );

        $model = Mage::getModel('salesrule/rule');

        $validateResult = $model->validateData(new Varien_Object($data));

        if ($validateResult == true) {

            if (isset($data['simple_action']) && $data['simple_action'] == 'by_percent'
                && isset($data['discount_amount'])) {
                $data['discount_amount'] = min(100, $data['discount_amount']);
            }

            if (isset($data['rule']['conditions'])) {
                $data['conditions'] = $data['rule']['conditions'];
            }

            if (isset($data['rule']['actions'])) {
                $data['actions'] = $data['rule']['actions'];
            }

            unset($data['rule']);

            $model->setData($data);

            $model->save();
        }
    }

    /*
     * Use this to calculate how much money off is allowed based on whats in the cart.
     */
    public function getDiscountAmount()
    {
        $customer   = Mage::getSingleton('customer/session')->getCustomer();
        $cart       = Mage::getModel('checkout/cart');
        $discountItems = array();
        /* Exclude some Business logic here */
        foreach ($cart->getQuote()->getAllVisibleItems() as $_item) {
            $product = Mage::getModel('catalog/product')->load($_item->getProduct()->getId());

            /* Business Logic to decide if this item is relevent */
            $discountItems[] = $_item;

        }

        // Calculate Discount
        $appliedDiscounts = 0;
        $discount = 0;
        foreach ($discountitem as $_item) {
            if ($appliedDiscounts < $allowed) {
                $i = 0;
                while ($appliedDiscounts < $allowed && $i < $_item->getQty()) {

                    $appliedDiscounts++;
                    $discount += $_item->getProduct()->getFinalPrice();

                    $i++;

                }
            }
        }
        return $discount;
    }
.

도움이 되었습니까?

해결책

이므로 미래에 비슷한 문제가 발생한 경우에는 문제의 원인이 무엇인지를 해결했습니다.수집 합계는 할인이 적용된 후에는 다시 계산되지 않도록 플래그를 설정했습니다.

Mage::getSingleton('checkout/cart')
        ->getQuote()
        ->setCouponCode(strlen($couponCode) ? $couponCode : '')
        ->collectTotals()
        ->save();
.

위를 다음과 같이 대체합니다.

Mage::getSingleton('checkout/cart')
            ->getQuote()
            ->setCouponCode(strlen($couponCode) ? $couponCode : '')
            ->save();
. 이것은 고객 크레딧을 적용하려고 시도 할 때 총계를 계산하고 제로 지불 결제를받을 수 있음을 의미합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 magento.stackexchange
scroll top