container = $container; } /** * @param $orderId * @return array * Возвращает по order_id необходимую информацию для формирования postback запросов * В виде ['order_id' => '', 'positions' => ['product_id' => '', 'price' => '', 'quantity' => '']] */ public function getPostbackData($orderId) { $order = new \WC_Order($orderId); $positions = array(); foreach ($order->get_items() as $item) { $productId = $item['product_id']; $quantity = $item['qty']; $product = new \WC_Product($productId); $price = $product->get_price(); $code = $this->container->getParameters()->getActionTariffCode($order, $item); array_push($positions, array( 'product_id' => $productId, 'quantity' => $quantity, 'price' => $price, 'action_code' => $code['action_code'], 'tariff_code' => $code['tariff_code'], )); } return array( 'order_id' => $orderId, 'positions' => $positions, ); } public function getCheckoutRetagParams() { return array( 'ad_order' => '', 'ad_amount' => 0, 'ad_products' => array( array('id' => '', 'number' => 1) ) ); } public function getCartRetagParams() { return array( 'ad_products' => array( array('id' => '', 'number' => 1) ) ); } public function getProductRetagParams() { return array( 'ad_product' => array( "id" => '', "vendor" => '', "price" => '', "url" => '', "picture" => '', "name" => '', "category" => '' ) ); } public function getCategoryRetagParams() { return array( 'ad_category' => '' ); } /** * Возвращает admitad uid */ public function getUserId() { $cookieName = $this->container->getSettings()->getCookieName(); if (isset($_COOKIE[$cookieName])) { return $_COOKIE[$cookieName]; } $userId = get_current_user_id(); if ($userId && $uid = get_user_meta($userId, 'admitad_uid', true)) { return $uid; } return null; } /** * Привязывает admitad uid, содержащийся в параметре $uid, к пользователю */ public function setUserId($uid) { $lifeTime = 45 * 60 * 60 * 24; $cookieName = $this->container->getSettings()->getCookieName(); setcookie($cookieName, $uid, time() + $lifeTime, '/'); if (isset($_SERVER['HTTP_HOST'])) { setcookie($cookieName, $uid, time() + $lifeTime, '/', '.' . $_SERVER['HTTP_HOST']); } if ($userId = get_current_user_id()) { update_user_meta($userId, 'admitad_uid', $uid); } } /** * @param \WC_Order $order * @param $item - информация о товаре в заказе * @return array - action_code и tariff_code в виде ['action_code' => '', 'tariff_code' => ''] */ public function getActionTariffCode($order, $item) { $cats = $this->getProductCategories($item['product_id']); $orderSum = $order->get_total() - $order->get_shipping_total(); $orderData = array( 'id' => $order->get_id(), 'sum' => $orderSum, 'email' => $order->get_billing_email(), 'phone' => $order->get_billing_phone(), ); $itemData = array('categories' => $cats); $code = $this->getTariffCode($itemData, $orderData); return $code; } /** * @param $productId * @return array * * Возвращает массив с категориями товара */ protected function getProductCategories($productId) { $rows = wp_get_post_terms($productId, 'product_cat'); $result = array_map(function ($row) { return $row->term_id; }, $rows); return $result; } /** * @param $itemData * @param $orderData * @return array * * Возвращает action_code и tariff_code по данным в orderData и itemData исходя из указанных настроек */ protected function getTariffCode($itemData, $orderData) { $map = $this->container->getSettings()->get('actions', 'actions') ?: array(); $tariff = null; $code = null; foreach ($map as $actionCode => $actionData) { if (!$this->isOrderAvailable($orderData, $actionData)) { continue; } foreach ($actionData['tariffs'] as $tariffCode => $tariffData) { if (null !== $tariff && !$this->compareTariffs($tariffData, $tariff, $itemData)) { continue; } $code = array('action_code' => $actionCode, 'tariff_code' => $tariffCode); $tariff = $tariffData; } } return $code ?: array('action_code' => null, 'tariff_code' => null); } /** * @param $orderData * @param $actionFilter * @return bool * * Проверяет принадлежность заказа к фильтру действия (цена, старый/новый пользователь, тип "покупка") */ protected function isOrderAvailable($orderData, $actionFilter) { if ($actionFilter['type'] != self::ACTION_TYPE_SALE) { return false; } $isNewUser = $this->isNewUser($orderData); $userType = $actionFilter['user_type']; if ($isNewUser && $userType != self::USER_TYPE_NEW && $userType != self::USER_TYPE_NONE) { return false; } if (!$isNewUser && $userType != self::USER_TYPE_OLD && $userType != self::USER_TYPE_NONE) { return false; } if (!empty($actionFilter['price_from']) || !empty($actionFilter['price_to'])) { $price = $orderData['sum']; $priceFrom = isset($actionFilter['price_from']) ? $actionFilter['price_from'] : 0; $priceTo = isset($actionFilter['price_to']) ? $actionFilter['price_to'] : 0; if ($price < $priceFrom) { return false; } if ($price > $priceTo && $priceTo >= $priceFrom) { return false; } } return true; } /** * @param $orderData * @return bool * * Проверяет по данным заказа и информации о текущем пользователе на старого и нового пользователя */ protected function isNewUser($orderData) { $queries = array( array('_billing_email' => $orderData['email']), array('_billing_phone' => $orderData['phone']), ); if ($userId = get_current_user_id()) { array_push($queries, array('_customer_user' => $userId)); } foreach ($queries as $key => $value) { $items = get_posts( array( 'numberposts' => -1, 'meta_key' => $key, 'meta_value' => $value, 'post_type' => wc_get_order_types(), 'post_status' => array_keys( wc_get_order_statuses() ), ) ); if (count($items) > 1) { return false; } } return true; } /** * @param $left * @param $right * @param $filter - фильтр, по которому производится сравнение * @return bool * * В случае, если оба тарифа подходят, * возвращает true если тариф $left актуальнее тарифа $right, false в противном случае */ protected function compareTariffs($left, $right, $filter) { $leftCategories = $left['categories']; $rightCategories = $right['categories']; foreach (array_reverse($filter['categories']) as $categoryId) { if (false !== array_search($categoryId, $leftCategories)) { return true; } if (false !== array_search($categoryId, $rightCategories)) { return false; } } if (!$leftCategories && $rightCategories) { return true; } if (!$rightCategories && $leftCategories) { return false; } return false; } }