Skip to content

Affiliate – get status of order

I have helper file below that check if the order is created or not and coupon code won’t work. but i want to check the status of the order first than allow coupon to work or not

  /**
     * @param $cacheKey
     *
     * @return bool
     */
    public static function hasCache($cacheKey)
    {
        if (isset(self::$_affCache[$cacheKey])) {
            return true;
        }

        return false;
    }

    /**
     * @param      $cacheKey
     * @param null $value
     */
    public static function saveCache($cacheKey, $value = null)
    {
        self::$_affCache[$cacheKey] = $value;
    }

    /**
     * @param $cacheKey
     *
     * @return mixed|null
     */
    public static function getCache($cacheKey)
    {
        if (isset(self::$_affCache[$cacheKey])) {
            return self::$_affCache[$cacheKey];
        }

        return null;
    }

    /**
     * @param      $value
     * @param null $code
     *
     * @return mixed
     */
    public function getAffiliateAccount($value, $code = null)
    {
        if ($code) {
            $account = $this->accountFactory->create()->load($value, $code);
        } else {
            $account = $this->accountFactory->create()->load($value);
        }

        return $account;
    }

    /**
     * @return mixed
     */
    public function getCurrentAffiliate()
    {
        $customerId = $this->_customerSession->getCustomerId();

        return $this->getAffiliateAccount($customerId, 'customer_id');
    }

    /**
     * Get affiliate key
     * if customer has referred by an other affiliate (has order already), get key from that order
     * else get key from cookie
     *
     * @return null|string
     */
    public function getAffiliateKey()
    {
        $key = $this->getAffiliateKeyFromCookie();
        if ($this->hasFirstOrder()) {
            $key = $this->getFirstAffiliateOrder()->getAffiliateKey();
        }

        return $key;
    }

    /**
     * Check customer has referred or not
     *
     * @return bool
     */
    public function hasFirstOrder()
    {
        $firstOrder = $this->getFirstAffiliateOrder();

        return $firstOrder && $firstOrder->getId();
    }

    /**
     * Get first order which has been referred by an affiliate
     *
     * @return mixed
     */
    public function getFirstAffiliateOrder()
    {
        $cacheKey = 'affiliate_first_order';
        if (!self::hasCache($cacheKey)) {
            $customer = $this->getCustomer();
            if ($customer && $customer->getId()) {
                $order = $this->createObject(Order::class)
                    ->getCollection()
                    ->addFieldToFilter('customer_id', $customer->getId());

                self::saveCache($cacheKey, $order->getFirstItem());
            }
        }

        return self::getCache($cacheKey);
    }