You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
cosmopet-architecture/wp-content/themes/cosmopet/modules/forms/module-ajax-controller.php

459 lines
17 KiB

<?php
require_once 'module-controller.php';
/* Вынести в FormHandler */
function get_current_user_data(){
if (is_user_logged_in()) {
$user_id = get_current_user_id();
$tg_username = get_user_meta($user_id, 'tg_username', true);
}
else{
$user_id = '';
$tg_username = '';
}
return array(
'user_id' => $user_id,
'tg_id' => $tg_username,
);
}
add_action('wp_ajax_blogauth_form', function() {
$enabledHandlers = ['b24', 'email', 'tg'];
$user_data = get_current_user_data();
$formData = json_decode($_POST['formData']);
$crmData = array(
'phone' => $formData['phone'],
'name' => $formData['name'],
'email' => $formData['email'],
'msg' => $formData['msg'],
'url' => $formData['url'],
'stage' => 'C4:NEW',
'fName' => 4,
'order_total' => 0,
'user_id' => $user_data['user_id'],
'method' => 'crm.deal.add',
'form_title' => 'Предложить статью или стать автором',
'is_subscribe' => false,
'order_id' => '',
);
process_form($enabledHandlers, $crmData);
});
add_action('wp_ajax_nopriv_blogauth_form', function() {
$enabledHandlers = ['b24', 'email', 'tg'];
$user_data = get_current_user_data();
$formData = json_decode($_POST['formData']);
$crmData = array(
'phone' => null,
'name' => $formData['name'],
'email' => $formData['email'],
'msg' => $formData['msg'],
'url' => $formData['url'],
'stage' => 'C4:NEW',
'fName' => 4,
'order_total' => 0,
'user_id' => $user_data['user_id'],
'method' => 'crm.deal.add',
'form_title' => 'Предложить статью или стать автором',
'is_subscribe' => false,
'order_id' => '',
);
process_form($enabledHandlers, $crmData);
});
add_action('wp_ajax_parthnership_form', function() {
$enabledHandlers = ['b24', 'email', 'tg'];
$user_data = get_current_user_data();
$formData = json_decode($_POST['formData']);
$crmData = array(
'phone' => $formData['phone'],
'name' => $formData['name'],
'email' => $formData['email'],
'msg' => 'Вид партнерства: ' . $formData['parthner_type'] . ' ' . $formData['msg'],
'url' => $formData['url'],
'stage' => 'C4:NEW',
'fName' => 4,
'order_total' => 0,
'user_id' => $user_data['user_id'],
'method' => 'crm.deal.add',
'form_title' => 'Стать партнером',
'is_subscribe' => false,
'order_id' => '',
);
process_form($enabledHandlers, $crmData);
});
add_action('wp_ajax_nopriv_parthnership_form', function() {
$enabledHandlers = ['b24', 'email', 'tg'];
$user_data = get_current_user_data();
$formData = json_decode($_POST['formData']);
$crmData = array(
'phone' => $formData['phone'],
'name' => $formData['name'],
'email' => $formData['email'],
'msg' => 'Вид партнерства: ' . $formData['parthner_type'] . ' ' . $formData['msg'],
'url' => $formData['url'],
'stage' => 'C4:NEW',
'fName' => 4,
'order_total' => 0,
'user_id' => $user_data['user_id'],
'method' => 'crm.deal.add',
'form_title' => 'Стать партнером',
'is_subscribe' => false,
'order_id' => '',
);
process_form($enabledHandlers, $crmData);
});
add_action('wp_ajax_contact_form', function() {
$enabledHandlers = ['b24', 'email', 'tg'];
$user_data = get_current_user_data();
$formData = json_decode($_POST['formData']);
$crmData = array(
'phone' => null,
'name' => $formData['name'],
'email' => $formData['email'],
'msg' => $formData['msg'],
'url' => $formData['url'],
'stage' => 'C7:NEW',
'fName' => 0,
'order_total' => 0,
'user_id' => $user_data['user_id'],
'method' => 'crm.lead.add',
'form_title' => 'Форма в футере',
'is_subscribe' => false,
'order_id' => '',
);
process_form($enabledHandlers, $crmData);
});
add_action('wp_ajax_nopriv_contact_form', function() {
$enabledHandlers = ['b24', 'email', 'tg'];
$user_data = get_current_user_data();
$formData = json_decode($_POST['formData']);
$crmData = array(
'phone' => null,
'name' => $formData['name'],
'email' => $formData['email'],
'msg' => $formData['msg'],
'url' => $formData['url'],
'stage' => 'C7:NEW',
'fName' => 0,
'order_total' => 0,
'user_id' => $user_data['user_id'],
'method' => 'crm.lead.add',
'form_title' => 'Форма в футере',
'is_subscribe' => false,
'order_id' => '',
);
process_form($enabledHandlers, $crmData);
});
add_action('wp_ajax_subscribe_form', function() {
$enabledHandlers = ['b24', 'email', 'tg'];
$user_data = get_current_user_data();
$formData = json_decode($_POST['formData']);
$crmData = array(
'phone' => null,
'name' => null,
'email' => $formData['email'],
'msg' => null,
'url' => $formData['url'],
'stage' => 'C2:NEW',
'fName' => 2,
'order_total' => 0,
'user_id' => $user_data['user_id'],
'method' => 'crm.deal.add',
'form_title' => 'Подписка на предложения',
'is_subscribe' => true,
'order_id' => '',
);
process_form($enabledHandlers, $crmData);
});
add_action('wp_ajax_nopriv_subscribe_form', function() {
$enabledHandlers = ['b24', 'email', 'tg'];
$user_data = get_current_user_data();
$formData = json_decode($_POST['formData']);
$crmData = array(
'phone' => null,
'name' => null,
'email' => $formData['email'],
'msg' => null,
'url' => $formData['url'],
'stage' => 'C2:NEW',
'fName' => 2,
'order_total' => 0,
'user_id' => $user_data['user_id'],
'method' => 'crm.deal.add',
'form_title' => 'Подписка на предложения',
'is_subscribe' => true,
'order_id' => '',
);
process_form($enabledHandlers, $crmData);
});
add_action('wp_ajax_to_know_form', function() {
$enabledHandlers = ['b24', 'tg'];
$user_data = get_current_user_data();
$raw = "sub_product=...&email=...&url=...";
parse_str($_POST['formData'], $formData);
$crmData = array(
'phone' => null,
'name' => null,
'email' => $formData['email'],
'msg' => 'Пользователь заинтересовался отсутсвующим продуктом' . $formData['sub_product'],
'url' => $formData['url'],
'stage' => 'C2:UC_QJ1M9Z',
'fName' => 2,
'order_total' => 0,
'user_id' => $user_data['user_id'],
'method' => 'crm.deal.add',
'form_title' => 'Подписка на отсутствующий продукт',
'is_subscribe' => false,
'order_id' => '',
);
process_form($enabledHandlers, $crmData);
});
add_action('wp_ajax_nopriv_to_know_form', function() {
$enabledHandlers = ['b24', 'tg'];
$user_data = get_current_user_data();
$raw = "sub_product=...&email=...&url=...";
parse_str($_POST['formData'], $formData);
$crmData = array(
'phone' => null,
'name' => null,
'email' => $formData['email'],
'msg' => 'Пользователь заинтересовался отсутсвующим продуктом' . $formData['sub_product'],
'url' => $formData['url'],
'stage' => 'C2:UC_QJ1M9Z',
'fName' => 2,
'order_total' => 0,
'user_id' => $user_data['user_id'],
'method' => 'crm.deal.add',
'form_title' => 'Подписка на отсутствующий продукт',
'is_subscribe' => false,
'order_id' => '',
);
process_form($enabledHandlers, $crmData);
process_form($enabledHandlers, $crmData);
});
function process_form($enabledHandlers, $crmData = array()) {
$formData = $_POST['formData'];
$handler = FormHandlerFactory::getHandler($enabledHandlers);
$response = $handler->handle($formData, $crmData);
wp_send_json($response);
}
// Отправляем данные в Bitrix24 при создании заказа
add_action('woocommerce_checkout_order_created', 'send_order_to_bitrix_on_create', 10, 1);
function send_order_to_bitrix_on_create($order) {
$order_id = $order->get_id();
$already_sent = $order->get_meta('_order_sent');
if (!$already_sent) {
send_order_data($order_id);
// Помечаем заказ как отправленный
$order->update_meta_data('_order_sent', '1');
$order->save();
}
}
function send_order_data($order_id) {
$order = wc_get_order($order_id);
// 1. Получаем данные заказа
$customer_name = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
$customer_phone = $order->get_billing_phone();
$customer_email = $order->get_billing_email();
$order_total = round_price_with_tax($order->get_total());
$order_comment = '';
$utm = get_utm_data()['utm_source'];
$url = '';
$fName = 2;
// 2. Формируем список товаров с полной ценой (включая НДС)
foreach ($order->get_items() as $item) {
$product = $item->get_product();
// Используем get_total_tax() + get_total() для получения полной цены с НДС
$item_total_without_tax = $item->get_total();
$item_tax = $item->get_total_tax();
$item_total_with_tax = round_price_with_tax($item_total_without_tax + $item_tax);
$order_comment .= sprintf(
"%s x %s = %s\n",
$product->get_name(),
$item->get_quantity(),
strip_tags(wc_price($item_total_with_tax))
);
}
// 3. Добавляем информацию о промокодах, если они использовались
$coupons = $order->get_coupon_codes();
if (!empty($coupons)) {
$order_comment .= "\n=== ПРОМОКОДЫ ===\n";
foreach ($coupons as $coupon_code) {
$coupon = new WC_Coupon($coupon_code);
$discount_amount = round_price_with_tax($order->get_discount_total());
$order_comment .= "Промокод: {$coupon_code}\n";
$order_comment .= "Скидка: " . strip_tags(wc_price($discount_amount)) . "\n";
}
}
$order_comment .= "\n=== ДАННЫЕ ДОСТАВКИ ===\n";
$order_comment .= "Город: " . $order->get_billing_city() . "\n";
$order_comment .= "Адрес: " . $order->get_billing_address_1() . "\n";
if ($order->get_billing_address_2()) {
$order_comment .= "Доп. адрес: " . $order->get_billing_address_2() . "\n";
}
$order_comment .= "Способ доставки: " . $order->get_shipping_method() . "\n";
$order_comment .= "Комментарий к заказу: " . $order->get_customer_note() . "\n";
if (is_user_logged_in()) {
$user_id = get_current_user_id();
} else {
$user_id = '';
}
$form_title = 'Покупка на сайте';
$formData = [
// Основные данные
'TITLE' => 'Заказ #' . $order_id,
'NAME' => $customer_name,
'PHONE' => $customer_phone,
'EMAIL' => $customer_email,
'USER_ID' => $user_id,
'ORDER_ID' => $order_id,
'ORDER_TOTAL' => $order_total,
'PAYMENT_METHOD' => $order->get_payment_method_title(),
'COMMENTS' => $clean_order_comment,
// Адрес (префикс ADDR_)
'ADDR_CITY' => $order->get_billing_city(),
'ADDR_STREET' => $order->get_billing_address_1(),
'ADDR_STREET2' => $order->get_billing_address_2(),
// UTM-метки (префикс UTM_)
'UTM_SOURCE' => $utm,
'UTM_MEDIUM' => get_utm_data()['utm_medium'] ?? '',
'UTM_CAMPAIGN' => get_utm_data()['utm_campaign'] ?? '',
// Системные поля
'SOURCE' => 'WooCommerce',
'FNAME' => $fName,
];
// Добавляем товары (префикс PRODUCT_1_, PRODUCT_2_ и т.д.)
$product_index = 1;
$product_summary = "🛒 Состав заказа:\n\n";
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$product_name = $product->get_name();
$product_qty = $item->get_quantity();
$product_total_without_tax = $item->get_total();
$product_tax = $item->get_total_tax();
$product_total_with_tax = round_price_with_tax($product_total_without_tax + $product_tax);
$product_sku = $product->get_sku();
$formData["PRODUCT_{$product_index}_NAME"] = $product_name;
$formData["PRODUCT_{$product_index}_QTY"] = $product_qty;
$formData["PRODUCT_{$product_index}_PRICE"] = $product_total_with_tax;
$formData["PRODUCT_{$product_index}_SKU"] = $product_sku;
// Добавляем в текстовую сводку с полной ценой
$product_summary .= "{$product_index}) {$product_name}\n";
$product_summary .= " Кол-во: {$product_qty}\n";
$product_summary .= " Сумма: " . strip_tags(wc_price($product_total_with_tax)) . "\n";
if ($product_sku) {
$product_summary .= " Артикул: {$product_sku}\n";
}
$product_summary .= "\n";
$product_index++;
}
// Добавляем информацию о промокодах в сводку товаров
$coupons = $order->get_coupon_codes();
if (!empty($coupons)) {
$product_summary .= "=== ПРОМОКОДЫ ===\n";
foreach ($coupons as $coupon_code) {
$coupon = new WC_Coupon($coupon_code);
$discount_amount = round_price_with_tax($order->get_discount_total());
$product_summary .= "Промокод: {$coupon_code}\n";
$product_summary .= "Скидка: " . strip_tags(wc_price($discount_amount)) . "\n";
}
$product_summary .= "\n";
}
// Функция для очистки текста от HTML-сущностей
function clean_text_for_telegram($text) {
// Удаляем HTML-теги
$text = strip_tags($text);
// Заменяем HTML-сущности на обычные символы
$text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
// Убираем лишние пробелы
$text = preg_replace('/\s+/', ' ', $text);
return trim($text);
}
$message = "📋 Данные формы:\n\n";
foreach ($formData as $key => $value) {
if (is_array($value)) {
$value = implode(', ', $value); // на случай, если в значении массив
}
$message .= sprintf("%s: %s\n", $key, clean_text_for_telegram($value));
}
// Очищаем тексты от HTML-сущностей для Telegram
$clean_product_summary = clean_text_for_telegram($product_summary);
$clean_order_comment = clean_text_for_telegram($order_comment);
$crmData = array(
'phone' => $customer_phone,
'name' => $customer_name,
'email' => $customer_email,
'msg' => $clean_product_summary,
'url' => null,
'stage' => 'C2:UC_ZMY1QV',
'fName' => 2,
'order_total' => $order_total,
'user_id' => $user_id,
'method' => 'crm.deal.add',
'form_title' => 'Заказ на сайте',
'is_subscribe' => false,
'order_id' => $order_id,
);
$handler = FormHandlerFactory::getHandler(['tg', 'b24']);
$response = $handler->handle($formData, $crmData);
}
add_action('woocommerce_payment_complete', 'notify_order_paid', 10, 1);
function notify_order_paid($order_id) {
$order = wc_get_order($order_id);
$formData = [
'TITLE' => 'Заказ #' . $order_id . ' оплачен',
'ORDER_ID' => $order_id,
'PAYMENT_METHOD' => $order->get_payment_method_title(),
'ORDER_TOTAL' => round_price_with_tax($order->get_total()),
'SOURCE' => 'WooCommerce',
];
$handler = FormHandlerFactory::getHandler(['tg']);
$handler->handle($formData, []);
global $site_env;
if ($site_env->site_region == 'ru'){
$b24Handler = new b24Handler();
$b24Handler->b24_update_deal_stage_by_order_id($order_id);
}
}
?>