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.
280 lines
13 KiB
280 lines
13 KiB
<?php
|
|
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
|
|
|
|
use Bitrix\Main\Config\Option;
|
|
use Bitrix\Sale;
|
|
use Bitrix\Main\Loader;
|
|
|
|
$response = array();
|
|
|
|
try {
|
|
if ($_SERVER["REQUEST_METHOD"] == "POST") {
|
|
if (!Loader::includeModule('sale')) {
|
|
$response = array(
|
|
'success' => false,
|
|
'message' => 'Модуль Интернет-магазин не подключен'
|
|
);
|
|
} else {
|
|
$name = trim($_POST["name"]);
|
|
$phone = trim($_POST["phone"]);
|
|
$email = trim($_POST["email"]);
|
|
$deliveryMethod = trim($_POST["delivery_method"]);
|
|
$pickupAddress = trim($_POST["pickup_address"]);
|
|
$address = trim($_POST["address"]);
|
|
$comment = trim($_POST["comment"]);
|
|
$paymentMethod = trim($_POST["payment_method"]);
|
|
$fastProduct = trim($_POST["fast_product"]);
|
|
|
|
if (empty($name) || empty($phone)) {
|
|
$response = array(
|
|
'success' => false,
|
|
'message' => 'Заполните обязательные поля (Имя и телефон)'
|
|
);
|
|
} else {
|
|
try {
|
|
$fUserId = Sale\Fuser::getId();
|
|
$basketInfo = array();
|
|
|
|
if (empty($fastProduct)) {
|
|
// Стандартная корзина пользователя
|
|
$basket = Sale\Basket::loadItemsForFUser($fUserId, SITE_ID);
|
|
|
|
if ($basket->isEmpty()) {
|
|
$response = array(
|
|
'success' => false,
|
|
'message' => 'Корзина пуста'
|
|
);
|
|
header('Content-Type: application/json');
|
|
echo json_encode($response, JSON_UNESCAPED_UNICODE);
|
|
return;
|
|
}
|
|
|
|
foreach ($basket as $basketItem) {
|
|
$basketInfo[] = array(
|
|
'name' => $basketItem->getField('NAME'),
|
|
'quantity' => $basketItem->getQuantity(),
|
|
'price' => $basketItem->getPrice(),
|
|
'product_id' => $basketItem->getProductId(),
|
|
'id' => $basketItem->getId()
|
|
);
|
|
}
|
|
} else {
|
|
// Быстрый заказ — создаём пустую корзину вручную
|
|
$basket = Sale\Basket::create(SITE_ID);
|
|
|
|
$item = $basket->createItem('catalog', 0); // фиктивный product_id
|
|
$item->setFields(array(
|
|
'NAME' => 'Заказ - ' . $fastProduct,
|
|
'QUANTITY' => 1,
|
|
'PRICE' => 0
|
|
));
|
|
|
|
$basketInfo[] = array(
|
|
'name' => 'Заказ - ' . $fastProduct,
|
|
'quantity' => 1,
|
|
'price' => 0,
|
|
'product_id' => 0,
|
|
'id' => 'virtual'
|
|
);
|
|
}
|
|
|
|
// Получаем тип плательщика
|
|
$personTypes = \CSalePersonType::GetList(
|
|
array("SORT" => "ASC"),
|
|
array("ACTIVE" => "Y", "LID" => SITE_ID)
|
|
);
|
|
|
|
$personTypeId = 1;
|
|
if ($personType = $personTypes->Fetch()) {
|
|
$personTypeId = $personType['ID'];
|
|
}
|
|
|
|
// Создаем заказ
|
|
$order = Sale\Order::create(SITE_ID, $fUserId);
|
|
$order->setPersonTypeId($personTypeId);
|
|
$order->setBasket($basket);
|
|
|
|
// Устанавливаем свойства заказа
|
|
$propertyCollection = $order->getPropertyCollection();
|
|
|
|
foreach ($propertyCollection as $property) {
|
|
$propertyCode = $property->getField('CODE');
|
|
|
|
switch ($propertyCode) {
|
|
case 'FIO':
|
|
case 'NAME':
|
|
$property->setValue($name);
|
|
break;
|
|
case 'PHONE':
|
|
$property->setValue($phone);
|
|
break;
|
|
case 'EMAIL':
|
|
if ($email) {
|
|
$property->setValue($email);
|
|
}
|
|
break;
|
|
case 'ADDRESS':
|
|
if ($deliveryMethod == 'service-delivery' && $address) {
|
|
$property->setValue($address);
|
|
}
|
|
break;
|
|
case 'COMMENT':
|
|
if ($comment) {
|
|
$property->setValue($comment);
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Создаем отгрузку
|
|
$shipmentCollection = $order->getShipmentCollection();
|
|
|
|
foreach ($shipmentCollection as $shipment) {
|
|
if (!$shipment->isSystem()) {
|
|
$shipmentCollection->deleteItem($shipment);
|
|
}
|
|
}
|
|
|
|
$shipment = $shipmentCollection->createItem();
|
|
|
|
try {
|
|
$deliveryServices = Sale\Delivery\Services\Manager::getActiveList();
|
|
if (!empty($deliveryServices)) {
|
|
$deliveryId = array_keys($deliveryServices)[0];
|
|
$shipment->setField('DELIVERY_ID', $deliveryId);
|
|
$shipment->setField('ALLOW_DELIVERY', 'Y');
|
|
}
|
|
} catch (Exception $e) {
|
|
// Продолжаем без доставки
|
|
}
|
|
|
|
$shipmentItemCollection = $shipment->getShipmentItemCollection();
|
|
foreach ($basket as $basketItem) {
|
|
$item = $shipmentItemCollection->createItem($basketItem);
|
|
$item->setQuantity($basketItem->getQuantity());
|
|
}
|
|
|
|
// Создаем оплату
|
|
$paymentCollection = $order->getPaymentCollection();
|
|
|
|
foreach ($paymentCollection as $payment) {
|
|
$paymentCollection->deleteItem($payment);
|
|
}
|
|
|
|
$payment = $paymentCollection->createItem();
|
|
|
|
try {
|
|
$paySystemServices = Sale\PaySystem\Manager::getList(array(
|
|
'filter' => array('ACTIVE' => 'Y'),
|
|
'order' => array('SORT' => 'ASC')
|
|
))->fetchAll();
|
|
|
|
if (!empty($paySystemServices)) {
|
|
$paySystemId = $paySystemServices[0]['ID'];
|
|
$payment->setField('PAY_SYSTEM_ID', $paySystemId);
|
|
$payment->setField('SUM', $order->getPrice());
|
|
}
|
|
} catch (Exception $e) {
|
|
// Продолжаем без платежной системы
|
|
}
|
|
|
|
// Сохраняем заказ
|
|
$result = $order->save();
|
|
|
|
if ($result->isSuccess()) {
|
|
$orderId = $order->getId();
|
|
$orderAccountNumber = $order->getField('ACCOUNT_NUMBER');
|
|
|
|
$logInfo = "Заказ создан: ID={$orderId}, USER_ID={$fUserId}, Товаров в корзине: " . count($basketInfo);
|
|
file_put_contents($_SERVER["DOCUMENT_ROOT"] . "/local/logs/orders.log",
|
|
date('Y-m-d H:i:s') . " - " . $logInfo . " - " . json_encode($basketInfo, JSON_UNESCAPED_UNICODE) . "\n",
|
|
FILE_APPEND | LOCK_EX);
|
|
|
|
$orderPrice = $order->getPrice();
|
|
$currency = $order->getCurrency();
|
|
$formattedPrice = \CCurrencyLang::CurrencyFormat($orderPrice, $currency);
|
|
|
|
// Отправляем уведомление
|
|
CEvent::Send(
|
|
"SALE_NEW_ORDER",
|
|
SITE_ID,
|
|
array(
|
|
"ORDER_ID" => $orderId,
|
|
"ORDER_DATE" => date("d.m.Y H:i:s"),
|
|
"USER_NAME" => $name,
|
|
"USER_PHONE" => $phone,
|
|
"USER_EMAIL" => $email ?: '',
|
|
"PRICE" => $formattedPrice,
|
|
"CURRENCY" => $currency,
|
|
"EMAIL" => Option::get("main", "email_from"),
|
|
"FAST_PRODUCT" => $fastProduct // Можно использовать в шаблоне письма!
|
|
)
|
|
);
|
|
|
|
// Очищаем корзину ТОЛЬКО если это был обычный заказ
|
|
if (empty($fastProduct)) {
|
|
try {
|
|
$basketForClear = Sale\Basket::loadItemsForFUser($fUserId, SITE_ID);
|
|
$basketForClear->clearCollection();
|
|
$basketForClear->save();
|
|
|
|
file_put_contents($_SERVER["DOCUMENT_ROOT"] . "/local/logs/orders.log",
|
|
date('Y-m-d H:i:s') . " - Корзина очищена для заказа ID={$orderId}\n",
|
|
FILE_APPEND | LOCK_EX);
|
|
} catch (Exception $e) {
|
|
file_put_contents($_SERVER["DOCUMENT_ROOT"] . "/local/logs/orders.log",
|
|
date('Y-m-d H:i:s') . " - Ошибка очистки корзины для заказа ID={$orderId}: " . $e->getMessage() . "\n",
|
|
FILE_APPEND | LOCK_EX);
|
|
}
|
|
}
|
|
|
|
$response = array(
|
|
'success' => true,
|
|
'message' => 'Заказ успешно оформлен',
|
|
'order_id' => $orderId,
|
|
'account_number' => $orderAccountNumber,
|
|
'admin_link' => "/bitrix/admin/sale_order_view.php?ID={$orderId}",
|
|
'redirect' => '/personal/orders/?ORDER_ID=' . $orderId,
|
|
'debug_info' => array(
|
|
'person_type_id' => $personTypeId,
|
|
'fuser_id' => $fUserId,
|
|
'site_id' => SITE_ID,
|
|
'price' => $orderPrice,
|
|
'currency' => $currency,
|
|
'basket_items' => count($basketInfo),
|
|
'items' => $basketInfo,
|
|
'fast_product' => $fastProduct
|
|
)
|
|
);
|
|
} else {
|
|
$errors = $result->getErrorMessages();
|
|
$response = array(
|
|
'success' => false,
|
|
'message' => 'Ошибка при создании заказа: ' . implode(', ', $errors),
|
|
'errors' => $errors
|
|
);
|
|
}
|
|
} catch (Exception $e) {
|
|
$response = array(
|
|
'success' => false,
|
|
'message' => 'Произошла ошибка: ' . $e->getMessage(),
|
|
'trace' => $e->getTraceAsString()
|
|
);
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
$response = array(
|
|
'success' => false,
|
|
'message' => 'Неверный метод запроса'
|
|
);
|
|
}
|
|
} catch (Exception $e) {
|
|
$response = array(
|
|
'success' => false,
|
|
'message' => 'Критическая ошибка: ' . $e->getMessage()
|
|
);
|
|
}
|
|
|
|
header('Content-Type: application/json');
|
|
echo json_encode($response, JSON_UNESCAPED_UNICODE);
|
|
|