Удаление заказов через скрипт

Материал из Umicms
Версия от 07:15, 27 марта 2025; Bvolkov (обсуждение | вклад)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к:навигация, поиск


Актуально для любой версии сайта до 24 версии включительно


Если заказов накопилось слишком много, можно использовать специальный скрипт для очистки заказов. Его необходимо назвать install.php и загрузить в корневую папку сайта (там где config.ini)

После того как скрипт будет в папке необходимо перейти по адресу https://Ваш_домен/install.php


Пример работающего скрипта:

Удаление заказов.jpg

Готовый код для скрипта, самое главное замените данные базы данных, больше ничего в скрипте менять не нужно.

 <?php
header('Content-Encoding: none');
/*
 * Скрипт для удаления всех заказов с реальным выводом прогресса
 */

// 1. Отключаем буферизацию полностью
@apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 0);
@ini_set('output_buffering', 0);
@ini_set('implicit_flush', 1);
ob_implicit_flush(true);
ob_end_flush();

// 2. Настройки сервера
ini_set('memory_limit', '512M');
set_time_limit(0);
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 3. Ручные настройки БД (ЗАМЕНИТЕ НА СВОИ!)
$dbConfig = [
    'host' => 'localhost',
    'user' => 'ваш_логин_mysql',
    'pass' => 'ваш_пароль_mysql',
    'name' => 'имя_базы_umi'
];

// 4. HTML-шапка (выводится сразу)
echo <<<HTML
<!DOCTYPE html>
<html>
<head>
    <title>Удаление заказов</title>
    <meta charset="UTF-8">
    <style>
        body { font-family: Arial; margin: 20px; }
        #progress { 
            width: 100%; background: #f0f0f0; padding: 10px;
            border-radius: 5px; margin: 20px 0;
        }
        #progress-bar {
            height: 20px; background: #4CAF50; width: 0%;
            border-radius: 3px; transition: width 0.3s;
        }
        #progress-text { margin-top: 5px; }
        #log {
            max-height: 300px; overflow-y: auto;
            border: 1px solid #ddd; padding: 10px;
            margin-bottom: 20px;
        }
        .log-entry { margin: 5px 0; }
        #restart-btn {
            padding: 10px 20px;
            background: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        #restart-btn:hover {
            background: #45a049;
        }
        #restart-btn:disabled {
            background: #cccccc;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
    <h2>Удаление всех заказов</h2>
    <div id="progress">
        <div id="progress-bar"></div>
        <div id="progress-text">Инициализация...</div>
    </div>
    <div id="log"></div>
    <button id="restart-btn" onclick="location.reload()">Повторить</button>
    <script>
        function scrollLog() {
            var log = document.getElementById('log');
            log.scrollTop = log.scrollHeight;
        }
    </script>
HTML;

// 5. Принудительный вывод
echo str_pad('', 2048, ' ');
flush();

// 6. Основной код
try {
    // Подключение к MySQL
    addLog("Подключение к MySQL...");
    $db = new mysqli($dbConfig['host'], $dbConfig['user'], $dbConfig['pass'], $dbConfig['name']);
    if ($db->connect_error) {
        throw new Exception("MySQL: " . $db->connect_error);
    }
    addLog("Успешно подключено к MySQL");

    // Подключение ядра UMI
    if (!file_exists('./standalone.php')) {
        throw new Exception("Файл standalone.php не найден");
    }
    require_once './standalone.php';
    addLog("Ядро UMI подключено");

    // Авторизация
    session_start();
    $objects = umiObjectsCollection::getInstance();
    $svId = $objects->getObjectIdByGUID('system-supervisor');
    $_SESSION['user_id'] = $svId;
    addLog("Авторизованы как супервайзер");

    // Получаем тип заказа
    $orderType = umiObjectTypesCollection::getInstance()->getTypeByGUID('emarket-order');
    if (!$orderType) {
        throw new Exception("Тип заказа не найден");
    }
    addLog("Тип заказа ID: {$orderType->getId()}");

    // Получаем общее количество
    $total = $db->query("SELECT COUNT(*) FROM cms3_objects WHERE type_id = '{$orderType->getId()}'")->fetch_row()[0];
    addLog("Всего заказов: $total");
    updateProgress(0, "Начало удаления...");

    // Пакетное удаление
    $batchSize = 500;
    $deleted = 0;
    
    for ($offset = 0; $offset < $total; $offset += $batchSize) {
        $result = $db->query("
            SELECT id FROM cms3_objects 
            WHERE type_id = '{$orderType->getId()}'
            LIMIT $offset, $batchSize
        ");
        
        while ($row = $result->fetch_assoc()) {
            $objects->delObject($row['id']);
            $deleted++;
            
            // Обновляем прогресс каждые 50 заказов
            if ($deleted % 50 == 0) {
                $percent = min(100, round(($offset / $total) * 100));
                updateProgress($percent, "Удалено: $deleted ($percent%)");
                addLog("Удален заказ #{$row['id']}", false);
            }
        }
        
        // Очистка памяти
        if (function_exists('gc_collect_cycles')) gc_collect_cycles();
        usleep(10000); // 0.01 сек
    }
    
    updateProgress(100, "Готово! Удалено: $deleted");
    addLog("Операция завершена успешно", true);
    $db->close();

} catch (Exception $e) {
    addLog("ОШИБКА: " . $e->getMessage(), true);
    updateProgress(0, "Произошла ошибка");
}

// 7. Функции вывода
function addLog($message, $isError = false) {
    $color = $isError ? 'red' : '#666';
    echo "<script>
        var log = document.getElementById('log');
        log.innerHTML += '<div class=\"log-entry\" style=\"color: '.$color.'\">'
            + new Date().toLocaleTimeString() + ' - ' + ".json_encode($message)."
            + '</div>';
        scrollLog();
    </script>";
    flush();
}

function updateProgress($percent, $message) {
    echo "<script>
        document.getElementById('progress-bar').style.width = '".$percent."%';
        document.getElementById('progress-text').innerHTML = ".json_encode($message).";
    </script>";
    flush();
}

echo "</body></html>";