990 lines
36 KiB
PHP
990 lines
36 KiB
PHP
<?php
|
||
|
||
// Регистрация страницы настроек
|
||
|
||
$b->admin_page_set("content", "settings_products", "Настройки товаров", array(), "settings_checkout");
|
||
$b->admin_page_set("settings_products", "settings_checkout","Оформление заказа", array(), "settings_checkout");
|
||
|
||
$b->setting_register("shipping_method_1", "Стоимость доставки - Почта России", "plain_text");
|
||
$b->setting_register("shipping_method_2", "Стоимость доставки - Курьер СДЕК", "plain_text");
|
||
$b->setting_register("shipping_method_3", "Стоимость доставки - Курьером Почты России (EMS)", "plain_text");
|
||
|
||
function settings_checkout()
|
||
{
|
||
global $b;
|
||
$b->template_load(bive_get_settings_template_path(), array("settings_list" => array("shipping_method_1", "shipping_method_2", "shipping_method_3")));
|
||
}
|
||
|
||
$b->event_add("bive_product_one_click", "bive_product_one_click");
|
||
|
||
function bive_product_one_click($args)
|
||
{
|
||
global $b;
|
||
$search = new Search(array(
|
||
"class" => "Product",
|
||
"terms" => array("item_id" => $args["product_id"])
|
||
));
|
||
$pages = $search->collect();
|
||
if(!count($pages)) {
|
||
http_response_code(404);
|
||
echo "Not found";
|
||
return;
|
||
}
|
||
$page = $pages[0];
|
||
$b->template_load("productCart/one_click.php", array("product" => $page));
|
||
exit();
|
||
}
|
||
|
||
// Один товар
|
||
|
||
$b->router_add("/product/%", function () { product_page(); }, array("get"));
|
||
|
||
$product_images = new Multifield(array("fields" => array("image" => array("plain_image", "Изображения"))));
|
||
$b->field_register("product_images", $product_images);
|
||
|
||
$product_variations = new Multifield(array("fields" => array("title" => array("plain_text", "Название вариации"), "product_slug" => array("plain_text", "Ярлык товара"))));
|
||
$b->field_register("product_variations", $product_variations);
|
||
|
||
$product_technical_features = new Multifield(array("fields" => array("name" => array("plain_text", "Имя"), "value" => array("plain_text", "Значение"), "tip" => array("plain_text", "Подсказка"))));
|
||
$b->field_register("product_technical_features", $product_technical_features);
|
||
|
||
$product_attribute_field = new AttributeField();
|
||
$b->field_register("product_attribute_field", $product_attribute_field);
|
||
|
||
function product_page()
|
||
{
|
||
global $b;
|
||
$slug = $b->router_get_segment(1);
|
||
|
||
$search = new Search(array(
|
||
"class" => "Product",
|
||
"terms" => array("item_slug" => $slug)
|
||
));
|
||
|
||
$pages = $search->collect();
|
||
|
||
if(!count($pages)) {
|
||
http_response_code(404);
|
||
$b->template_load("404.php");
|
||
return;
|
||
}
|
||
|
||
$page = $pages[0];
|
||
$b->ls_set_key("page", $page);
|
||
|
||
$parent = $page->get_parent();
|
||
|
||
$breadcrumbs = array(
|
||
array("Каталог", "/catalog/")
|
||
);
|
||
|
||
$parents_breadcrumbs = array();
|
||
get_parents_breadcrumbs($parents_breadcrumbs, $parent);
|
||
$breadcrumbs = array_merge($breadcrumbs, $parents_breadcrumbs);
|
||
|
||
$price = $page->get_price();
|
||
|
||
$b->title_set($page->get_item_name() . " купить по цене " . $price . " руб в интернет-магазине GNRT с доставкой - гарантия, отзывы");
|
||
$b->meta_add("description", $page->get_item_name() . " по цене " . $price . " руб в интернет-магазине GNRT ✓ Официальный поставщик генераторного оборудования ✓ Собственные инжиниринговые разработки ✓ Выездные сервисные инженеры ✓ Доставляем продукцию по РФ");
|
||
|
||
$b->meta_add("viewport", "width=device-width, user-scalable=no");
|
||
$b->link_add(array("rel" => "canonical", "href" => $b->router_get_canonical_uri()));
|
||
|
||
if($parent) {
|
||
$parent_title = $parent->get_item_name();
|
||
$parent_slug = $parent->get_item_slug();
|
||
$breadcrumbs[] = array($parent_title, "/category/" . $parent_slug . "/");
|
||
$breadcrumbs[] = array($page->get_item_name(), $b->router_get_canonical_uri());
|
||
}
|
||
|
||
$b->ls_set_key("breadcrumbs", $breadcrumbs);
|
||
$b->template_load("pages/product.php");
|
||
}
|
||
|
||
$b->router_add("/product-row/%", "product_row", array("get"));
|
||
|
||
function product_row()
|
||
{
|
||
global $b;
|
||
$slug = $b->router_get_segment(1);
|
||
|
||
$search = new Search(array(
|
||
"class" => "Product",
|
||
"terms" => array("item_slug" => $slug)
|
||
));
|
||
|
||
$pages = $search->collect();
|
||
|
||
if(!count($pages)) {
|
||
http_response_code(404);
|
||
echo "Not found";
|
||
return;
|
||
}
|
||
|
||
$page = $pages[0];
|
||
$b->template_load("productCategory/product_row.php", array("product" => $page));
|
||
}
|
||
|
||
function get_product_row_params($params): array
|
||
{
|
||
$power = $fuel = $engine = "";
|
||
foreach ($params as $key => $param) {
|
||
if($power == "" && stripos($param["name"], "Мощность") !== false) $power = $param["value"];
|
||
if($fuel == "" && stripos($param["name"], "Вид топлива") !== false) $fuel = $param["value"];
|
||
if($engine == "" && stripos($param["name"], "Двигатель") !== false) $engine = $param["value"];
|
||
}
|
||
return array("fuel" => $fuel, "power" => $power, "engine" => $engine);
|
||
}
|
||
|
||
function get_product_short_params($params): array
|
||
{
|
||
$list = array();
|
||
$power = array();
|
||
$fuel = array();
|
||
$engine = array();
|
||
$producer = array();
|
||
$napr = array();
|
||
foreach ($params as $key => $param) {
|
||
$lover_name = mb_strtolower($param["name"]);
|
||
if($list[$lover_name]) continue;
|
||
if(stripos($lover_name, "мощность") !== false) $power[] = $param;
|
||
if(stripos($lover_name, "напряжение") !== false) $napr[] = $param;
|
||
if(stripos($lover_name, "вид топлива") !== false) $fuel[] = $param;
|
||
if($lover_name == "двигатель") $engine[] = $param;
|
||
if(stripos($lover_name, "производитель") !== false) $producer[] = $param;
|
||
$list[$lover_name] = 1;
|
||
}
|
||
return array("fuel" => $fuel, "power" => $power, "engine" => $engine, "napr" => $napr, "producer" => $producer);
|
||
}
|
||
|
||
function get_parents_breadcrumbs(&$array, $parent)
|
||
{
|
||
if(is_bool($parent)) return true;
|
||
$parent_item = $parent->get_parent();
|
||
if(!$parent_item) return true;
|
||
array_unshift($array, array($parent_item->get_item_name(), "/category/" . $parent_item->get_item_slug() . "/"));
|
||
get_parents_breadcrumbs($array, $parent_item);
|
||
}
|
||
|
||
// Категория
|
||
|
||
$b->router_add("/category/%", "product_category_page", array("get"));
|
||
|
||
$termins_field = new Multifield(array("fields" => array("title" => array("plain_text", "Заголовок"), "text" => array("plain_bigtext", "Текст"))));
|
||
$b->field_register("product_termins_field", $termins_field);
|
||
|
||
$news_field = new Multifield(array("fields" => array("item_id" => array("plain_text", "ID Новости"))));
|
||
$b->field_register("product_news_field", $news_field);
|
||
|
||
function product_category_page()
|
||
{
|
||
global $b;
|
||
$slug = $b->router_get_segment(1);
|
||
|
||
$search = new Search(array(
|
||
"class" => "ProductCategory",
|
||
"terms" => array("item_slug" => $slug)
|
||
));
|
||
|
||
$pages = $search->collect();
|
||
|
||
if(!count($pages)) {
|
||
http_response_code(404);
|
||
$b->template_load("404.php");
|
||
return;
|
||
}
|
||
|
||
$page = $pages[0];
|
||
$b->ls_set_key("page", $page);
|
||
|
||
|
||
if($page->get_prop("seo_title") && $page->get_prop("seo_title") != "")
|
||
$b->title_set($page->get_prop("seo_title"));
|
||
else $b->title_set($page->get_item_name());
|
||
|
||
$b->meta_add("description", $page->get_prop("seo_description"));
|
||
$b->meta_add("keywords", $page->get_prop("seo_keywords"));
|
||
$b->meta_add("viewport", "width=device-width, user-scalable=no");
|
||
$b->link_add(array("rel" => "canonical", "href" => $b->router_get_canonical_uri()));
|
||
|
||
$parent = $page->get_parent();
|
||
|
||
$breadcrumbs = array(
|
||
array("Каталог", "/catalog/")
|
||
);
|
||
|
||
if($parent) {
|
||
$parent_title = $parent->get_item_name();
|
||
$parent_slug = $parent->get_item_slug();
|
||
$parents_breadcrumbs = array();
|
||
get_parents_breadcrumbs($parents_breadcrumbs, $parent);
|
||
|
||
$breadcrumbs = array_merge($breadcrumbs, $parents_breadcrumbs);
|
||
$breadcrumbs[] = array($parent_title, "/category/" . $parent_slug . "/");
|
||
}
|
||
|
||
$breadcrumbs[] = array($page->get_item_name(), $b->router_get_canonical_uri());
|
||
|
||
$b->ls_set_key("breadcrumbs", $breadcrumbs);
|
||
$b->template_load("pages/productCategory.php");
|
||
}
|
||
|
||
$b->event_add("bive_product_category", "bive_product_category");
|
||
|
||
function bive_product_category($args)
|
||
{
|
||
global $b;
|
||
$slug = $b->router_get_segment(1);
|
||
|
||
$search = new Search(array(
|
||
"class" => "ProductCategory",
|
||
"terms" => array("item_slug" => $slug)
|
||
));
|
||
|
||
$pages = $search->collect();
|
||
|
||
if(!count($pages)) {
|
||
http_response_code(404);
|
||
$b->template_load("404.php");
|
||
return;
|
||
}
|
||
|
||
$page = $pages[0];
|
||
$b->ls_set_key("page", $page);
|
||
$b->template_load("productCategory/block.php", array("params" => $args, "url" => $b->router_get_canonical_uri()), false);
|
||
exit();
|
||
}
|
||
|
||
function category_search($params): array
|
||
{
|
||
global $b;
|
||
$query = category_query($params);
|
||
$result = $b->db_query($query["query_string"], $query["variables"], true);
|
||
return items_fill($result);
|
||
}
|
||
|
||
function items_fill($db_result)
|
||
{
|
||
log_message("-- Начинаю заполнять айтемы " .time());
|
||
$items = array();
|
||
foreach ($db_result as $key => $item_db) {
|
||
$item = new $item_db["item_class"]($item_db["item_id"]);
|
||
$item->fill_main_parent($item_db["item_parent"]);
|
||
$items[] = $item;
|
||
}
|
||
log_message("-- Закончил заполнять айтемы " .time());
|
||
return $items;
|
||
}
|
||
|
||
function category_search_count($params)
|
||
{
|
||
global $b;
|
||
$query = category_query($params, true);
|
||
$result = $b->db_query($query["query_string"], $query["variables"], true);
|
||
return $result[0]["count"];
|
||
}
|
||
|
||
function category_search_attributes($params): array
|
||
{
|
||
global $b;
|
||
$variables = array();
|
||
log_message("-- Формирую параметры для атрибутов " .time());
|
||
|
||
$category_id = $params["category_id"];
|
||
$attributes = $params["attributes"];
|
||
|
||
$parent_where = " links_category.parent_item_id = ? ";
|
||
$variables[] = $category_id;
|
||
|
||
$attributes_query = "";
|
||
foreach ($attributes as $key => $attribute_id) {
|
||
$attributes_query .= "JOIN bive_items_links AS links_attributes".$key." ON links_attributes".$key.".parent_item_id = links_category.child_item_id AND links_attributes".$key.".items_class = 'Product-Attribute_Item' AND links_attributes".$key.".child_item_id = ? ";
|
||
$variables[] = $attribute_id;
|
||
}
|
||
|
||
|
||
$ranges = $params["ranges"] ?? array();
|
||
$price_inner = "";
|
||
$price_where = "";
|
||
|
||
foreach ($ranges as $key => $range) {
|
||
$min_value = $range["min_value"];
|
||
$max_value = $range["max_value"];
|
||
$range_name = $range["name"];
|
||
|
||
if ($min_value > 0 && $max_value > 0 && $max_value > $min_value) {
|
||
$price_inner .= " INNER JOIN `bive_items_index` AS `bip$key` ON `bip$key`.`item_id` = links_category.child_item_id AND `bip$key`.`prop_key` = '" . $range_name . "' ";
|
||
$price_where .= " AND `bip$key`.`prop_value` >= ? AND `bip$key`.`prop_value` <= ? ";
|
||
$variables[] = $min_value;
|
||
$variables[] = $max_value;
|
||
}
|
||
}
|
||
|
||
$where_sale = "";
|
||
if($params["sale_price"] == 1) {
|
||
$price_inner .= " INNER JOIN `bive_items_props` AS `bip` ON `bip`.`item_id` = links_category.child_item_id AND `bip`.`prop_key` = 'sale_percent' ";
|
||
$where_sale = " AND CAST(`bip`.`prop_value` AS SIGNED) > 0 ";
|
||
}
|
||
|
||
$price_inner .= " INNER JOIN `bive_items_index` AS `bip_price` ON `bip_price`.`item_id` = links_category.child_item_id AND `bip_price`.`prop_key` = 'price' INNER JOIN `bive_items_index` AS `bip_power` ON `bip_power`.`item_id` = links_category.child_item_id AND `bip_power`.`prop_key` = 'power' ";
|
||
$full_query = "SELECT bive_items.* FROM bive_items JOIN bive_items_intermediate AS links_category ON links_category.items_class = 'ProductCategory-Product-Attribute_Item' AND " . $parent_where . " AND links_category.germ_item_id = bive_items.item_id " . $attributes_query . $price_inner . $price_where . $where_sale . " GROUP BY bive_items.item_id";
|
||
|
||
log_message("-- Получаю атрибуты из базы " .time());
|
||
$result = $b->db_query($full_query, $variables, true);
|
||
log_message("-- Заполняю атрибуты " .time());
|
||
return items_fill($result);
|
||
}
|
||
|
||
function category_query($params, $count = false): array
|
||
{
|
||
$variables = array();
|
||
|
||
$category_id = $params["category_id"];
|
||
$attributes = $params["attributes"];
|
||
|
||
$parent_inner = " INNER JOIN bive_items_links AS links_category ON links_category.items_class = 'ProductCategory-Product' AND links_category.parent_item_id = ? AND links_category.child_item_id = product_items.item_id ";
|
||
$variables[] = $category_id;
|
||
|
||
$attributes_query = "1";
|
||
foreach ($attributes as $key => $attribute_id) {
|
||
$attributes_query .= " AND EXISTS (SELECT 1 FROM bive_items_links WHERE bive_items_links.parent_item_id = `product_items`.`item_id` AND bive_items_links.child_item_id = ?)";
|
||
$variables[] = $attribute_id;
|
||
}
|
||
|
||
$ranges = $params["ranges"] ?? array();
|
||
$price_inner = "";
|
||
$price_where = "";
|
||
|
||
foreach ($ranges as $key => $range) {
|
||
$min_value = $range["min_value"];
|
||
$max_value = $range["max_value"];
|
||
$range_name = $range["name"];
|
||
|
||
if ($min_value > 0 && $max_value > 0 && $max_value > $min_value) {
|
||
$price_inner .= " INNER JOIN `bive_items_index` AS `bip$key` ON `product_items`.`item_id` = `bip$key`.`item_id` AND `bip$key`.`prop_key` = '" . $range_name . "' ";
|
||
$price_where .= " AND `bip$key`.`prop_value` >= ? AND `bip$key`.`prop_value` <= ? ";
|
||
$variables[] = $min_value;
|
||
$variables[] = $max_value;
|
||
}
|
||
}
|
||
|
||
$where_sale = "";
|
||
if($params["sale_price"] == 1) {
|
||
$where_sale = " AND CAST(`bip`.`prop_value` AS SIGNED) > 0 ";
|
||
$price_inner .= " INNER JOIN `bive_items_props` AS `bip` ON `product_items`.`item_id` = `bip`.`item_id` AND `bip`.`prop_key` = 'sale_percent' ";
|
||
}
|
||
|
||
$search_phrase_query = "";
|
||
if(isset($params["search_phrase"])) {
|
||
$searchTherm = "%".$params["search_phrase"]."%";
|
||
$search_phrase_query = " AND `product_items`.`item_name` LIKE ?";
|
||
$variables[] = $searchTherm;
|
||
}
|
||
|
||
$page = intval($params["page"]) ?? 1;
|
||
$products_per_page = intval($params["products_per_page"]) ?? 30;
|
||
$offset = intval(($page - 1) * $products_per_page);
|
||
$limit = " LIMIT " . $offset . ", " . $products_per_page;
|
||
$select = "*";
|
||
|
||
if($count) {
|
||
$limit = "";
|
||
$select = "COUNT(*) as `count`";
|
||
}
|
||
|
||
$price_inner .= " INNER JOIN `bive_items_index` AS `bip_price` ON `product_items`.`item_id` = `bip_price`.`item_id` AND `bip_price`.`prop_key` = 'price' INNER JOIN `bive_items_index` AS `bip_power` ON `product_items`.`item_id` = `bip_power`.`item_id` AND `bip_power`.`prop_key` = 'power' ";
|
||
$order = " ORDER BY (`bip_price`.`prop_value` = 0), `bip_price`.`prop_value` ASC, `bip_power`.`prop_value` ASC ";
|
||
|
||
$query_string = "SELECT " . $select . " FROM `bive_items` AS `product_items` " . $parent_inner . $price_inner . " WHERE " . $attributes_query . $price_where . $where_sale . $search_phrase_query . $order. $limit;
|
||
return array("query_string" => $query_string, "variables" => $variables);
|
||
}
|
||
|
||
function attribute_get_ids()
|
||
{
|
||
global $b;
|
||
$attribute_ids = array();
|
||
foreach ($_GET as $get_key => $get_param) {
|
||
$parse_field = explode("_", $get_key);
|
||
$search = new Search(array(
|
||
"class" => "Attribute",
|
||
"terms" => array("item_slug" => $parse_field[1])
|
||
));
|
||
$pages = $search->collect();
|
||
if(!$pages) continue;
|
||
$page = $pages[0];
|
||
$parent_id = $page->item_id;
|
||
$query = new Search(array(
|
||
"class" => "Attribute_Item",
|
||
"terms" => array("item_slug" => $get_param),
|
||
"parent_id" => $parent_id
|
||
));
|
||
$attributes = $query->collect();
|
||
if(!$attributes) continue;
|
||
$attribute = $attributes[0];
|
||
$attribute_ids[] = $attribute->item_id;
|
||
}
|
||
return $attribute_ids;
|
||
}
|
||
|
||
function attribute_get_values($attribute_id, $numeric = false)
|
||
{
|
||
global $b;
|
||
$childs = array();
|
||
$class_name = "Attribute_Item";
|
||
|
||
$class_condition = "";
|
||
if($class_name != "") $class_condition = " AND i.`item_class` = '" . $class_name . "' ";
|
||
|
||
$order = " ORDER BY `i`.`item_name` ASC";
|
||
if($numeric) $order = " ORDER BY CAST(`i`.`item_name` AS SIGNED) ASC";
|
||
|
||
$query = "SELECT * FROM `bive_items_links` as l JOIN `bive_items` as i ON i.`item_id` = l.`child_item_id` " . $class_condition . " WHERE l.`parent_item_id` = ?" . $order;
|
||
$child_list = $b->db_query($query, [ $attribute_id ], true);
|
||
if(!count($child_list)) return $childs;
|
||
|
||
foreach ($child_list as $key => $db_child) {
|
||
$child = new $db_child["item_class"]($db_child["item_id"]);
|
||
$child->set_parent($db_child["item_parent"], true);
|
||
$childs[] = $child;
|
||
}
|
||
|
||
return $childs;
|
||
}
|
||
|
||
// Корзина
|
||
|
||
$b->router_add("/cart/", function () { product_cart_page(); }, array("get"));
|
||
|
||
function product_cart_page() {
|
||
global $b;
|
||
$b->title_set("Корзина - " . $b->setting_get_value("bive_site_name"));
|
||
$b->meta_add("viewport", "width=device-width, user-scalable=no");
|
||
$b->meta_add("description", $b->setting_get_value("main_page_description"));
|
||
$b->link_add(array("rel" => "canonical", "href" => $b->router_get_canonical_uri()));
|
||
|
||
$breadcrumbs = array(
|
||
array("Корзина", "/cart/")
|
||
);
|
||
$b->ls_set_key("breadcrumbs", $breadcrumbs);
|
||
$b->template_load("pages/cart.php");
|
||
}
|
||
|
||
class Cart {
|
||
private array $products = array(); // Массив с товарами из корзины
|
||
private bool $loaded = false; // Загружена ли корзина
|
||
|
||
// Подсчет цифр корзины
|
||
public function cart_total_price(): array
|
||
{
|
||
global $b;
|
||
|
||
$sale_sum = 0;
|
||
$total_sum = 0;
|
||
$regular_sum = 0;
|
||
|
||
$products = $this->get_product_items();
|
||
foreach ($products as $key => $cart_product) {
|
||
$product = $cart_product["item"];
|
||
$count = $cart_product["count"];
|
||
$total_price = $product->get_price();
|
||
$regular_price = $product->get_regular_price();
|
||
$sale_delta = ($regular_price - $total_price) * $count;
|
||
$regular_sum += $regular_price * $count;
|
||
$total_sum += $total_price * $count;
|
||
$sale_sum += $sale_delta;
|
||
}
|
||
|
||
// $pay_method = $this->get_pay_method();
|
||
$final_sum = $total_sum + $this->get_shipping_price();
|
||
|
||
// if($pay_method == 1) {
|
||
// $final_sum = $final_sum * 0.95;
|
||
// $sale_sum += $final_sum * 0.05;
|
||
// }
|
||
|
||
$coupon_id = $b->session_get("coupon_id");
|
||
if($coupon_id) {
|
||
$coupon = $b->get_item_by_id($coupon_id);
|
||
if($coupon) {
|
||
$coupon_sum = $coupon->get_prop("sum");
|
||
$coupon_percent = $coupon->get_prop("percent");
|
||
$coupon_final_sum = $final_sum;
|
||
if($coupon_percent) $coupon_final_sum = $final_sum * (1 - ($coupon_percent / 100));
|
||
$coupon_final_sum = $coupon_final_sum - $coupon_sum;
|
||
$sale_sum += $final_sum - $coupon_final_sum;
|
||
$final_sum = $coupon_final_sum;
|
||
}
|
||
}
|
||
|
||
return array(
|
||
"sale_sum" => $sale_sum,
|
||
"total_sum" => $total_sum,
|
||
"regular_sum" => $regular_sum,
|
||
"final_sum" => $final_sum
|
||
);
|
||
}
|
||
|
||
// Очистить всю корзину
|
||
public function clear()
|
||
{
|
||
global $b;
|
||
$b->session_set("cart", json_encode(array()));
|
||
return $this->get_session_cart();
|
||
}
|
||
|
||
// Прибавить товар в корзине
|
||
public function product_add($product_id)
|
||
{
|
||
if($product_id <= 0) return false;
|
||
$session_cart = &$this->get_session_cart();
|
||
if(!isset($session_cart[$product_id])) $session_cart[$product_id] = 0;
|
||
$session_cart[$product_id] += 1;
|
||
return $session_cart[$product_id];
|
||
}
|
||
|
||
// Уменьшить товар в корзине
|
||
public function product_remove($product_id)
|
||
{
|
||
if($product_id <= 0) return false;
|
||
$session_cart = &$this->get_session_cart();
|
||
if(!isset($session_cart[$product_id])) $session_cart[$product_id] = 0;
|
||
$session_cart[$product_id] -= 1;
|
||
if($session_cart[$product_id] < 1) { unset($session_cart[$product_id]); return 0; }
|
||
return $session_cart[$product_id];
|
||
}
|
||
|
||
// Удалить товар из корзины
|
||
public function product_delete($product_id): int
|
||
{
|
||
if($product_id <= 0) return false;
|
||
$session_cart = &$this->get_session_cart();
|
||
unset($session_cart[$product_id]);
|
||
return 0;
|
||
}
|
||
|
||
// Сохранить корзину
|
||
public function save(): array
|
||
{
|
||
global $b;
|
||
$session_cart = &$this->get_session_cart();
|
||
$b->session_set("cart", json_encode($session_cart));
|
||
return $this->products;
|
||
}
|
||
|
||
// Получить количество
|
||
public function get_count()
|
||
{
|
||
$count = 0;
|
||
$session_cart = &$this->get_session_cart();
|
||
foreach ($session_cart as $product_id => $product_count)
|
||
if($product_count > 0) $count += $product_count;
|
||
return $count;
|
||
}
|
||
|
||
// Получить товары из корзины
|
||
public function get_product_items()
|
||
{
|
||
$items = array();
|
||
$session_cart = &$this->get_session_cart();
|
||
foreach ($session_cart as $product_id => $product_count) {
|
||
$items[] = array(
|
||
"item" => new Product($product_id),
|
||
"count" => $product_count
|
||
);
|
||
}
|
||
return $items;
|
||
}
|
||
|
||
// Получить содержимое корзины в сессии
|
||
private function &get_session_cart()
|
||
{
|
||
global $b;
|
||
if($this->loaded) return $this->products;
|
||
$cart = $b->session_get("cart");
|
||
if($cart === false) return $this->create_session_cart();
|
||
$this->products = json_decode($cart, true);
|
||
$this->loaded = true;
|
||
return $this->products;
|
||
}
|
||
|
||
// Создать содержимое корзины в сессии
|
||
private function &create_session_cart()
|
||
{
|
||
global $b;
|
||
$b->session_set("cart", json_encode(array()));
|
||
return $this->get_session_cart();
|
||
}
|
||
|
||
// Получить способ оплаты
|
||
public function get_pay_method()
|
||
{
|
||
global $b;
|
||
$payment_method = $b->session_get("payment_method");
|
||
if($payment_method === false) return 1;
|
||
return $payment_method;
|
||
}
|
||
|
||
// Получить стоимость доставки
|
||
public function get_shipping_price()
|
||
{
|
||
global $b;
|
||
$shipping_method = $this->get_session_shipping();
|
||
if($shipping_method == 0) return 0;
|
||
$price = $b->setting_get_value("shipping_method_" . $shipping_method);
|
||
return $price;
|
||
}
|
||
|
||
// Установить метод доставки
|
||
public function set_shipping_method($method)
|
||
{
|
||
global $b;
|
||
$b->session_set("shipping", $method);
|
||
return $this->get_shipping_price();
|
||
}
|
||
|
||
// Обновить информацию покупателя
|
||
public function update_customer($key, $value): bool
|
||
{
|
||
global $b;
|
||
if($key == "shipping_method") {
|
||
$this->set_shipping_method($value);
|
||
return true;
|
||
}
|
||
$b->session_set($key, $value);
|
||
return true;
|
||
}
|
||
|
||
// Получить содержимое доставки в сессии
|
||
private function get_session_shipping()
|
||
{
|
||
global $b;
|
||
$shipping = $b->session_get("shipping");
|
||
if($shipping === false) return $this->create_session_shipping();
|
||
return $shipping;
|
||
}
|
||
|
||
// Создать содержимое доставки в сессии
|
||
private function create_session_shipping()
|
||
{
|
||
global $b;
|
||
$b->session_set("shipping", 1);
|
||
return $this->get_session_shipping();
|
||
}
|
||
|
||
// Применить купон
|
||
public function coupon_apply($coupon_code): bool
|
||
{
|
||
global $b;
|
||
$search = new Search(array(
|
||
"class" => "Coupon",
|
||
"terms" => array("item_name" => $coupon_code)
|
||
));
|
||
$items = $search->collect();
|
||
if(!count($items)) return false;
|
||
$coupon = $items[0];
|
||
$b->session_set("coupon_id", $coupon->item_id);
|
||
return true;
|
||
}
|
||
|
||
public function coupon_deny(): bool
|
||
{
|
||
global $b;
|
||
$b->session_set("coupon_id", null);
|
||
return true;
|
||
}
|
||
|
||
// Есть ли товар
|
||
public function hasProduct($product_id): bool
|
||
{
|
||
$session_cart = &$this->get_session_cart();
|
||
foreach ($session_cart as $db_product_id => $product_count)
|
||
if($db_product_id == $product_id && $product_count > 0) return true;
|
||
return false;
|
||
}
|
||
|
||
// Количество товаров по ID
|
||
public function getProductCount($product_id):int
|
||
{
|
||
$session_cart = &$this->get_session_cart();
|
||
foreach ($session_cart as $db_product_id => $product_count)
|
||
if($db_product_id == $product_id) return $product_count;
|
||
return 0;
|
||
}
|
||
}
|
||
|
||
global $cart;
|
||
$cart = new Cart();
|
||
|
||
$b->router_add("/cart/frame/", function () {
|
||
global $b;
|
||
$b->template_load("productCart/block.php");
|
||
}, array("get"));
|
||
|
||
$b->router_add("/cart/add/", function () {
|
||
global $cart;
|
||
$product_id = intval($_POST["product_id"]);
|
||
$product_count = $cart->product_add($product_id);
|
||
$cart_count = $cart->get_count();
|
||
$cart->save();
|
||
echo json_encode(array("product_count" => $product_count, "cart_count" => $cart_count));
|
||
}, array("post"));
|
||
|
||
$b->router_add("/cart/remove/", function () {
|
||
global $cart;
|
||
$product_id = intval($_POST["product_id"]);
|
||
$product_count = $cart->product_remove($product_id);
|
||
$cart_count = $cart->get_count();
|
||
$cart->save();
|
||
echo json_encode(array("product_count" => $product_count, "cart_count" => $cart_count));
|
||
}, array("post"));
|
||
|
||
$b->router_add("/cart/delete/", function () {
|
||
global $cart;
|
||
$product_id = intval($_POST["product_id"]);
|
||
$product_count = $cart->product_delete($product_id);
|
||
$cart_count = $cart->get_count();
|
||
$cart->save();
|
||
echo json_encode(array("product_count" => $product_count, "cart_count" => $cart_count));
|
||
}, array("post"));
|
||
|
||
$b->router_add("/cart/coupon_apply/", function () {
|
||
global $cart;
|
||
$coupon_code = $_POST["coupon_code"];
|
||
$result = $cart->coupon_apply($coupon_code);
|
||
echo json_encode(array("ok" => $result));
|
||
}, array("post"));
|
||
|
||
$b->router_add("/cart/coupon_deny/", function () {
|
||
global $cart;
|
||
$cart->coupon_deny();
|
||
echo json_encode(array("ok" => true));
|
||
}, array("post"));
|
||
|
||
// Оформление заказа
|
||
|
||
$b->router_add("/checkout/", function () { product_checkout_page(); }, array("get"));
|
||
$b->router_add("/checkout/", function () { product_checkout_confirm(); }, array("post"));
|
||
|
||
function product_checkout_page()
|
||
{
|
||
global $b;
|
||
$b->title_set("Оформление заказа - " . $b->setting_get_value("bive_site_name"));
|
||
$b->meta_add("viewport", "width=device-width, user-scalable=no");
|
||
$b->meta_add("description", $b->setting_get_value("main_page_description"));
|
||
$b->link_add(array("rel" => "canonical", "href" => $b->router_get_canonical_uri()));
|
||
|
||
$breadcrumbs = array(
|
||
array("Оформление заказа", $b->router_get_canonical_uri())
|
||
);
|
||
$b->ls_set_key("breadcrumbs", $breadcrumbs);
|
||
$b->template_load("pages/checkout.php");
|
||
}
|
||
|
||
$order_cart = new Multifield(array("fields" => array("product_id" => array("plain_text", "ID товара"), "count" => array("plain_text", "Количество"))));
|
||
$b->field_register("order_cart", $order_cart);
|
||
|
||
function product_checkout_confirm()
|
||
{
|
||
global $b, $cart;
|
||
$order = new Order(0);
|
||
$order->create("Заказ от " . date("d.m.y"), "");
|
||
$person = $_POST["legal"];
|
||
|
||
foreach ($_POST as $key => $value) {
|
||
if($key == "shipping_method") {
|
||
if($value == 1) $order->set_prop($key, "Почтой России");
|
||
if($value == 2) $order->set_prop($key, "Курьером Почты России (EMS)");
|
||
if($value == 3) $order->set_prop($key, "Курьер СДЭК");
|
||
if($value == 0) $order->set_prop($key, "Самовывоз");
|
||
continue;
|
||
}
|
||
if($key == "payment_method") {
|
||
if($value == 1 && $person == 1) $order->set_prop($key, "Банковской картой онлайн");
|
||
if($value == 1 && $person == 2) $order->set_prop($key, "На рассчетный счет");
|
||
if($value == 2) $order->set_prop($key, "Картой при получении");
|
||
if($value == 0) $order->set_prop($key, "Наличными");
|
||
continue;
|
||
}
|
||
if($key == "payment_method") {
|
||
if($value == 1) $order->set_prop($key, "Банковской картой онлайн");
|
||
if($value == 2) $order->set_prop($key, "Картой при получении");
|
||
}
|
||
$order->set_prop($key, $value);
|
||
}
|
||
|
||
$cart_info = $cart->cart_total_price();
|
||
$order->set_prop("sum", $cart_info["final_sum"] . " руб.");
|
||
|
||
$product_list = array();
|
||
$products = $cart->get_product_items();
|
||
foreach ($products as $key => $product) {
|
||
$product_row = array();
|
||
$product_row["product_id"] = $product["item"]->item_id;
|
||
$product_row["count"] = $product["count"];
|
||
$product_list[] = $product_row;
|
||
}
|
||
|
||
$coupon_id = $b->session_get("coupon_id");
|
||
if($coupon_id) {
|
||
$coupon = $b->get_item_by_id($coupon_id);
|
||
if($coupon) $order->set_prop("promocode", $coupon->get_item_name());
|
||
}
|
||
|
||
$order->set_prop("order_cart", json_encode($product_list));
|
||
$cart->clear();
|
||
|
||
$b->session_set("order", $order->item_id);
|
||
order_tg_send(count($products), $cart_info["final_sum"], $order->item_id);
|
||
$b->router_redirect("/thanks-order/");
|
||
exit();
|
||
}
|
||
|
||
function order_tg_send($product_count, $product_sum, $order_id)
|
||
{
|
||
global $b;
|
||
$root_url = $b->router_get_root_uri();
|
||
$text = "<b> 🛒 Новый заказ:</b>\n\n";
|
||
|
||
if(isset($_POST["legal_name"])) $text .= "<b>Имя компании:</b> " . $b->get_view($_POST["legal_name"]) . "\n";
|
||
if(isset($_POST["name"])) $text .= "<b>Имя:</b> " . $b->get_view($_POST["name"]) . "\n";
|
||
if(isset($_POST["phone"])) $text .= "<b>Телефон:</b> " . $b->get_view($_POST["phone"]) . "\n";
|
||
if(isset($_POST["email"])) $text .= "<b>Email:</b> " . $b->get_view($_POST["email"]) . "\n";
|
||
if(isset($_POST["legal_address"])) $text .= "<b>Адрес:</b> " . $b->get_view($_POST["legal_address"]) . "\n";
|
||
if(isset($_POST["message"])) $text .= "\n<b>💬 Комментарий:</b> " . $b->get_view($_POST["comment"]) . "\n";
|
||
if(isset($_POST["address_region"])) $text .= "\n<b>📍 Регион:</b> " . $b->get_view($_POST["address_region"]) . "\n";
|
||
|
||
$text .= "\n<b>💳 Сумма:</b> " . $product_sum . "руб.\n";
|
||
$text .= "<b>📦 Количество товаров:</b> " . $product_count. "\n";
|
||
$text .= "\n<a href='" . $root_url . "/admin/?page=item_Order&item_id=" . $order_id . "'>Полная информация</a> ";
|
||
|
||
appeal_send_tg($text);
|
||
}
|
||
|
||
$b->router_add("/checkout/frame/", function () {
|
||
global $b;
|
||
$person = $_GET["person"] ?? 1;
|
||
$b->template_load("checkout/block.php", array("person" => $person));
|
||
}, array("get"));
|
||
|
||
$b->router_add("/checkout/update/", function () {
|
||
global $cart;
|
||
$key = $_POST["name"];
|
||
$value = $_POST["value"];
|
||
$cart->update_customer($key, $value);
|
||
echo json_encode(array("ok" => true));
|
||
}, array("post"));
|
||
|
||
// Спасибо за заказ
|
||
|
||
$b->router_add("/thanks-order/", function () { product_thanks(); }, array("get"));
|
||
|
||
function product_thanks()
|
||
{
|
||
global $b;
|
||
$b->title_set("Спасибо за заказ - " . $b->setting_get_value("bive_site_name"));
|
||
$b->meta_add("viewport", "width=device-width, user-scalable=no");
|
||
$b->meta_add("description", $b->setting_get_value("main_page_description"));
|
||
$b->link_add(array("rel" => "canonical", "href" => $b->router_get_canonical_uri()));
|
||
|
||
$breadcrumbs = array(
|
||
array("Спасибо за заказ", $b->router_get_canonical_uri())
|
||
);
|
||
$b->ls_set_key("breadcrumbs", $breadcrumbs);
|
||
$b->template_load("pages/thanks_order.php");
|
||
}
|
||
|
||
class Purchase
|
||
{
|
||
public int $purchase_id;
|
||
public Order $purchase;
|
||
|
||
public function __construct($purchase_id)
|
||
{
|
||
$this->purchase_id = $purchase_id;
|
||
$this->purchase = new Order($purchase_id);
|
||
}
|
||
|
||
// Получить товары заказа
|
||
public function get_product_items()
|
||
{
|
||
$items = array();
|
||
$products = $this->get_products_db();
|
||
if ($products === false) return false;
|
||
foreach ($products as $product_key => $product) {
|
||
$items[] = array(
|
||
"item" => new Product($product["product_id"]),
|
||
"count" => $product["count"]
|
||
);
|
||
}
|
||
return $items;
|
||
}
|
||
|
||
public function order_total_price(): array
|
||
{
|
||
global $b;
|
||
$sale_sum = 0;
|
||
$total_sum = 0;
|
||
$regular_sum = 0;
|
||
|
||
$products = $this->get_product_items();
|
||
foreach ($products as $key => $cart_product) {
|
||
$product = $cart_product["item"];
|
||
$count = $cart_product["count"];
|
||
$total_price = $product->get_price();
|
||
$regular_price = $product->get_regular_price();
|
||
$sale_delta = ($regular_price - $total_price) * $count;
|
||
$regular_sum += $regular_price * $count;
|
||
$total_sum += $total_price * $count;
|
||
$sale_sum += $sale_delta;
|
||
}
|
||
|
||
$coupon_name = $this->purchase->get_prop("promocode");
|
||
if($coupon_name) {
|
||
$search = new Search(array(
|
||
"class" => "Coupon",
|
||
"terms" => array("item_name" => $coupon_name)
|
||
));
|
||
$items = $search->collect();
|
||
if(count($items)) {
|
||
$coupon = $items[0];
|
||
$coupon_sum = $coupon->get_prop("sum");
|
||
$coupon_percent = $coupon->get_prop("percent");
|
||
$coupon_final_sum = $total_sum;
|
||
if($coupon_percent) $coupon_final_sum = $total_sum * (1 - ($coupon_percent / 100));
|
||
$coupon_final_sum = $coupon_final_sum - $coupon_sum;
|
||
$sale_sum += $total_sum - $coupon_final_sum;
|
||
}
|
||
}
|
||
|
||
return array(
|
||
"sale_sum" => $sale_sum,
|
||
"total_sum" => $total_sum,
|
||
"regular_sum" => $regular_sum,
|
||
"final_sum" => $this->purchase->get_prop("sum")
|
||
);
|
||
}
|
||
|
||
// Получить товары из базы
|
||
public function get_products_db()
|
||
{
|
||
return $this->purchase->get_prop_render_value("order_cart");
|
||
}
|
||
}
|
||
|
||
function sortArrayByName($array) {
|
||
usort($array, function($a, $b) {
|
||
return strcmp($a['title'], $b['title']);
|
||
});
|
||
return $array;
|
||
}
|
||
|
||
function sortArrayByNumeric($array) {
|
||
usort($array, function($a, $b) {
|
||
$a_val = intval(preg_replace('/[^0-9]/', "", $a['title']));
|
||
$b_val = intval(preg_replace('/[^0-9]/', "", $b['title']));
|
||
if(empty($a_val)) $a_val = 999999;
|
||
if(empty($b_val)) $b_val = 999999;
|
||
return $a_val > $b_val;
|
||
});
|
||
return $array;
|
||
} |