app.post("/api/cornerSectorsNew", (req, res) => {
    cornerSectors = req.body;

    // Вызываем функцию для обновления кругов
    adjustUsersAfterCornerSectorsUpdate();

    res.sendStatus(200);
});

app.post("/api/data", (req, res) => {
    const data = req.body;
    users = data.map((row, index) => ({
        user_name: row[0],
        code: row[1].toString(),
        player_id: row[2],
        total_user_points: 0,
        total_user_fish: 0,
        circles: row.slice(3).map((pair, i) => {
            const [opponent_number, sector] = pair;
            const opponent = data.find((r) => r[2] === opponent_number) || {};
            const opponent_name = opponent[0] || "Unknown Opponent";
            return {
                number: i + 1,
                status: i === 0 ? "active" : "inactive",
                index_circle: i + 1,
                second_circle: false,
                playerGame: {
                    approveState: 1,
                    number: row[2],
                    name: row[0],
                    fishCount: null,
                    points: 0,
                    total_points: 0,
                    sector: sector,
                },
                opponentGame: {
                    approveState: 1,
                    number: opponent_number,
                    name: opponent_name,
                    fishCount: null,
                    points: 0,
                    sector: sector,
                    total_points: 0,
                },
            };
        }),
    }));
    baseUsers = [...users];

    const usersWithEmptyName = users.filter(
        (user) => user.user_name === "Empty"
    );

    if (usersWithEmptyName.length > 0) {
        let finalNewUsers = users.map((user) => ({ ...user, circles: [] }));

        for (let i = 0; i < users[0].circles.length; i++) {
            let newUsers = users.map((user) => ({ ...user, circles: [] }));
            for (let j = 0; j < newUsers.length; j++) {
                const circle = users[j].circles[i];
                const newCircle = {
                    number: i + 1,
                    status: i === 0 ? "active" : "inactive",
                    index_circle: i + 1,
                    second_circle: false,
                    playerGame: circle.playerGame,
                    opponentGame: circle.opponentGame,
                };
                newUsers[j].circles.push(newCircle);
            }
            for (let j = 0; j < newUsers.length; j++) {
                const user = newUsers[j];
                const circle = newUsers[j].circles[0];
                if (circle.opponentGame.name === "Empty") {
                    const sectorEmpty = circle.opponentGame.sector;
                    const changeSectorEmpty = cornerSectors.includes(
                        sectorEmpty
                    )
                        ? 1
                        : -1;
                    let userNewOpponent;
                    let userNewOpponentIndex;
                    for (let k = 0; k < newUsers.length; k++) {
                        const opponent = newUsers[k];
                        if (
                            changeSectorEmpty === -1 &&
                            opponent.circles[0].playerGame.sector ===
                                sectorEmpty - 1 &&
                            opponent.player_id % 2 !== (i + 1) % 2
                        ) {
                            userNewOpponent = opponent;
                            userNewOpponentIndex = k;
                            break;
                        }
                    }
                    if (!userNewOpponent) {
                        for (let k = 0; k < newUsers.length; k++) {
                            const opponent = newUsers[k];
                            if (
                                changeSectorEmpty === 1 &&
                                opponent.circles[0].playerGame.sector ===
                                    sectorEmpty + 1 &&
                                opponent.player_id % 2 === (i + 1) % 2
                            ) {
                                userNewOpponent = opponent;
                                userNewOpponentIndex = k;
                                break;
                            }
                        }
                    }

                    if (userNewOpponent) {
                        const newCircleOpponent = {
                            number: i + 1,
                            index_circle: i + 1,
                            second_circle: true,
                            status: i === 0 ? "active" : "inactive",
                            playerGame: userNewOpponent.circles[0].playerGame,
                            opponentGame: circle.playerGame,
                        };
                        newUsers[userNewOpponentIndex].circles.push(
                            newCircleOpponent
                        );
                        newUsers[j].circles[0].opponentGame =
                            userNewOpponent.circles[0].playerGame;
                    } else {
                        console.log(
                            "Не найден оппонент для пользователя",
                            user.user_name
                        );
                    }
                }
            }
            for (let j = 0; j < newUsers.length; j++) {
                for (let k = 0; k < newUsers[j].circles.length; k++) {
                    finalNewUsers[j].circles.push(newUsers[j].circles[k]);
                }
            }
        }
        for (let j = 0; j < finalNewUsers.length; j++) {
            for (let k = 0; k < finalNewUsers[j].circles.length; k++) {
                const circle = finalNewUsers[j].circles[k];
                const newCircle = {
                    number: k + 1,
                    index_circle: circle.index_circle,
                    second_circle: circle.second_circle,
                    status: circle.status,
                    playerGame: circle.playerGame,
                    opponentGame: circle.opponentGame,
                };
                finalNewUsers[j].circles[k] = newCircle;
            }
        }
        users = finalNewUsers;
    }
    res.sendStatus(200);
});

function adjustUsersAfterCornerSectorsUpdate() {
    // 1. Удаляем все неактивные круги у пользователей
    users.forEach((user) => {
        user.circles = user.circles.filter(
            (circle) => circle.status !== "inactive"
        );
    });

    // 2. Определяем индекс последнего активного круга
    let lastActiveIndex = Math.max(
        0,
        ...users.map((user) =>
            user.circles.reduce(
                (maxIndex, circle) =>
                    (circle.status === "active" ||
                        circle.status === "completed") &&
                    circle.index_circle > maxIndex
                        ? circle.index_circle
                        : maxIndex,
                0
            )
        )
    );

    // 3. Начинаем пересоздавать круги с индекса lastActiveIndex + 1
    let startIndex = lastActiveIndex + 1;

    // 4. Инициализация finalNewUsers с уже имеющимися кругами
    let finalNewUsers = users.map((user) => ({
        ...user,
        circles: [...user.circles],
    }));

    let totalStages = Math.max(
        0,
        ...users.map((user) =>
            user.circles.reduce(
                (maxIndex, circle) =>
                    (circle.status === "active" ||
                        circle.status === "completed" ||
                        circle.status === "inactive") &&
                    circle.index_circle > maxIndex
                        ? circle.index_circle
                        : maxIndex,
                0
            )
        )
    );

    // 5. Пересоздаем круги с использованием логики из /api/data
    for (let i = startIndex - 1; i < totalStages; i++) {
        let newUsers = users.map((user) => ({ ...user, circles: [] }));

        // Создаем новый круг для каждого пользователя
        for (let j = 0; j < newUsers.length; j++) {
            const circle = baseUsers[j].circles[i];
            const newCircle = {
                number: i + 1,
                status: i === startIndex - 1 ? "active" : "inactive",
                index_circle: i + 1,
                second_circle: false,
                playerGame: circle.playerGame,
                opponentGame: circle.opponentGame,
            };
            newUsers[j].circles.push(newCircle);
        }

        // Применяем логику для формирования second_circle
        for (let j = 0; j < newUsers.length; j++) {
            const user = newUsers[j];
            const circle = newUsers[j].circles[0];
            if (circle.opponentGame.name === "Empty") {
                const sectorEmpty = circle.opponentGame.sector;
                const changeSectorEmpty = cornerSectors.includes(sectorEmpty)
                    ? 1
                    : -1;

                let userNewOpponent;
                let userNewOpponentIndex;

                // Ищем оппонента согласно логике
                for (let k = 0; k < newUsers.length; k++) {
                    const opponent = newUsers[k];
                    if (
                        changeSectorEmpty === -1 &&
                        opponent.circles[0].playerGame.sector ===
                            sectorEmpty - 1 &&
                        opponent.player_id % 2 !== (i + 1) % 2
                    ) {
                        userNewOpponent = opponent;
                        userNewOpponentIndex = k;
                        break;
                    }
                }
                if (!userNewOpponent) {
                    for (let k = 0; k < newUsers.length; k++) {
                        const opponent = newUsers[k];
                        if (
                            changeSectorEmpty === 1 &&
                            opponent.circles[0].playerGame.sector ===
                                sectorEmpty + 1 &&
                            opponent.player_id % 2 === (i + 1) % 2
                        ) {
                            userNewOpponent = opponent;
                            userNewOpponentIndex = k;
                            break;
                        }
                    }
                }
                if (userNewOpponent) {
                    const newCircleOpponent = {
                        number: i + 1,
                        index_circle: i + 1,
                        second_circle: true,
                        status: i === startIndex - 1 ? "active" : "inactive",
                        playerGame: userNewOpponent.circles[0].playerGame,
                        opponentGame: circle.playerGame,
                    };
                    newUsers[userNewOpponentIndex].circles.push(
                        newCircleOpponent
                    );
                    newUsers[j].circles[0].opponentGame =
                        userNewOpponent.circles[0].playerGame;
                } else {
                    console.log(
                        "Не найден оппонент для пользователя",
                        user.user_name
                    );
                }
            }
        }

        // Добавляем новые круги в finalNewUsers
        for (let j = 0; j < newUsers.length; j++) {
            for (let k = 0; k < newUsers[j].circles.length; k++) {
                finalNewUsers[j].circles.push(newUsers[j].circles[k]);
            }
        }
    }

    // 6. Обновляем пользователей
    for (let i = 0; i < users.length; i++) {
        users[i].circles = finalNewUsers[i].circles;
    }

    // 7. Отправляем обновленные данные клиентам
    io.emit("allUsersUpdated", users);
}
У меня в adjustUsersAfterCornerSectorsUpdate почему-то все круги inactive просто удаляются, хотя все круги со статусом inactive должны заново распределяться как в "/api/data" и как в "/api/data" должно происходить создание second circle === true кругов, а круги со стасума active и completed должны оставаться без изменений