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"
);
});
code
// 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 должны оставаться без изменений
It sounds like you're encountering an issue where all circles are being removed as "inactive" in the adjustUsersAfterCornerSectorsUpdate function, even though some should remain as "active" or "completed". This behavior likely stems from a few potential issues in your code. Let's walk through the possible causes and provide recommendations to address them.
1. Status Filtering Logic
Issue:
The primary step in your adjustUsersAfterCornerSectorsUpdate function is to remove all circles with a status of "inactive":
However, if none of the circles have a status that isn't exactly "inactive" (considering case sensitivity), this would result in the removal of all circles. For example, if some circles are labeled as "Inactive" (with an uppercase "I") or have leading/trailing spaces, they won't be correctly filtered out.
Recommendation:
Ensure Consistent Status Values: Verify that all circle statuses are consistently set to lowercase "inactive", "active", or "completed". Any inconsistency in casing or additional whitespace can cause the filter to malfunction.
Use Case-Insensitive Comparison: Modify the filter to be case-insensitive to avoid accidental mismatches. For example:
Debugging: Add logging before and after the filter to inspect the statuses of the circles:
javascript
users.forEach((user) => {
console.log(`Before filter for user ${user.user_name}:`, user.circles.map(c => c.status));
user.circles = user.circles.filter(
(circle) => circle.status.toLowerCase() !== "inactive"
);
console.log(`After filter for user ${user.user_name}:`, user.circles.map(c => c.status));
});
This will help you verify whether the filter is working as intended.
2. Initialization and Use of baseUsers
Issue:
The baseUsers array is set in the /api/data endpoint:
javascript
baseUsers = [...users];
However, in adjustUsersAfterCornerSectorsUpdate, you're using baseUsers[j].circles[i] without ensuring that baseUsers accurately represents the current state of users. If baseUsers isn't updated correctly after sectors are changed, it may lead to undefined or incorrect circle data being accessed.
Recommendation:
Ensure baseUsers is Up-to-Date: Whenever you modify users, ensure that baseUsers is also updated to reflect these changes. This could be done by updating baseUsers at the end of both the /api/data and adjustUsersAfterCornerSectorsUpdate functions.
Initialize baseUsers Appropriately: If adjustUsersAfterCornerSectorsUpdate can be called multiple times, ensure that baseUsers is correctly initialized and maintained to prevent stale data:
javascript
function adjustUsersAfterCornerSectorsUpdate() {
// Ensure baseUsers is up-to-date before proceeding
baseUsers = [...users];
// ... rest of your function
}
Alternatively, consider whether baseUsers is necessary or if you can work directly with users to simplify your logic.
3. Logic for Recreating Circles
Issue:
The process of recreating circles after filtering can be complex and may inadvertently discard or misassign circles. The loop starts from startIndex - 1 and runs until totalStages, which is determined by the maximum index_circle across all circles:
javascript
for (let i = startIndex - 1; i < totalStages; i++) {
// Circle recreation logic
}
If startIndex or totalStages are miscalculated, it can result in missing or overprocessing circles.
Recommendation:
Validate Indices: Add logging to confirm the values of startIndex, totalStages, and the range of i in the loop. Ensure they align with your expectations based on the current state of users and baseUsers.
javascript
console.log('Last Active Index:', lastActiveIndex);
console.log('Start Index:', startIndex);
console.log('Total Stages:', totalStages);
Simplify Logic if Possible: If feasible, simplify the logic for recreating circles. Ensure that circles being recreated maintain the necessary properties and relationships (e.g., second_circle assignments).
4. Handling "Empty" Opponents
Issue:
Your logic for reassigning opponents when opponentGame.name === "Empty" is intricate and might not cover all edge cases, especially after updating cornerSectors. If the condition for assigning new opponents isn't met correctly, you might fail to assign necessary circles, or inadvertently mark valid circles as "Empty".
Recommendation:
Thoroughly Test Opponent Reassignment: Implement additional logging within the opponent reassignment logic to ensure that opponents are being correctly identified and reassigned.
javascript
if (circle.opponentGame.name === "Empty") {
console.log(`Processing Empty opponent for user ${user.user_name}`);
// ... rest of the opponent reassignment logic
if (userNewOpponent) {
console.log(`Assigned new opponent ${userNewOpponent.user_name} to user ${user.user_name}`);
} else {
console.log(`No opponent found for user ${user.user_name}`);
}
}
Ensure Sector Logic is Correct: Verify that the logic determining changeSectorEmpty and selecting userNewOpponent aligns with your intended behavior when cornerSectors are updated.
5. Comprehensive Error Handling and Logging
Issue:
The function currently logs when an opponent isn't found, but more granular logging can help identify exactly where and why circles are being improperly removed or not reassigned.
Recommendation:
Add Detailed Logging: Implement logging at key points in the function to trace the flow of data and identify where things might be going wrong.
javascript
function adjustUsersAfterCornerSectorsUpdate() {
// Step 1: Remove inactive circles
users.forEach((user) => {
console.log(`User: ${user.user_name}, Circles before filter: ${user.circles.length}`);
user.circles = user.circles.filter(
(circle) => circle.status.toLowerCase() !== "inactive"
);
console.log(`User: ${user.user_name}, Circles after filter: ${user.circles.length}`);
});
// Continue with other steps, adding logs as necessary
// ...
}
Use Try-Catch Blocks: Wrap critical sections of your code in try-catch blocks to handle and log unexpected errors gracefully.
This approach improves readability and makes it easier to pinpoint where issues may arise.
7. Ensuring Data Consistency Between Requests
Issue:
If adjustUsersAfterCornerSectorsUpdate is invoked before the /api/data endpoint has fully processed or if there's concurrent access/modification of users and baseUsers, data inconsistencies could occur.
Recommendation:
Use Synchronization Mechanisms: Ensure that modifications to users and baseUsers are thread-safe and that one function completes its updates before another begins.
Validate Data Before Processing: Before performing operations in adjustUsersAfterCornerSectorsUpdate, confirm that users and baseUsers are in a consistent state.
Final Recommendations
Based on the analysis, here's a consolidated list of steps to help you resolve the issue:
Verify Status Values:
Ensure all circles have consistent and correctly cased status values ("active", "inactive", "completed").
Implement case-insensitive checks in your filtering logic.
Update and Maintain baseUsers:
Ensure baseUsers accurately reflects the current state of users whenever changes occur.
Consider whether baseUsers is necessary or if you can refactor to eliminate it.
Add Comprehensive Logging:
Implement detailed logging throughout adjustUsersAfterCornerSectorsUpdate to trace the flow and identify where circles are being incorrectly removed or not reassigned.
Refactor for Clarity:
Break down adjustUsersAfterCornerSectorsUpdate into smaller helper functions to improve readability and maintainability.
Ensure Correct Opponent Reassignment:
Verify that the logic for reassigning opponents when opponentGame.name === "Empty" is functioning as intended.
Add additional checks and logs to confirm opponents are being correctly identified and assigned.
Error Handling:
Implement try-catch blocks around critical sections to gracefully handle unexpected errors and provide informative logs.
Test Iteratively:
After making changes, test each part of the function thoroughly to ensure that circles are being correctly maintained, recreated, and updated without unintended deletions.
Example: Improved adjustUsersAfterCornerSectorsUpdate Function
Here's an example of how you might refactor and enhance your adjustUsersAfterCornerSectorsUpdate function with these recommendations in mind:
javascript
Conclusion
By implementing these recommendations, you should be able to identify and resolve the issue where circles are being incorrectly removed as "inactive". Ensuring consistent status values, maintaining synchronization between users and baseUsers, enhancing logging for better traceability, and refactoring for clarity will significantly improve the reliability and maintainability of your code.
If after these changes the issue persists, consider creating unit tests for each function to isolate and test individual components of your logic. This approach can help pinpoint the exact step where the unexpected behavior occurs.
Not yet included in a published release.
function adjustUsersAfterCornerSectorsUpdate() {
try {
console.log("Starting adjustUsersAfterCornerSectorsUpdate...");
// Step 1: Remove inactive circles
users.forEach((user) => {
console.log(`User: ${user.user_name}, Circles before filter: ${user.circles.length}`);
user.circles = user.circles.filter(
(circle) => circle.status.toLowerCase() !== "inactive"
);
console.log(`User: ${user.user_name}, Circles after filter: ${user.circles.length}`);
});
// Step 2: Determine the last active index
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
)
)
);
console.log("Last Active Index:", lastActiveIndex);
let startIndex = lastActiveIndex + 1;
console.log("Start Index:", startIndex);
// Step 3: Determine total stages
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
)
)
);
console.log("Total Stages:", totalStages);
// Step 4: Initialize finalNewUsers
let finalNewUsers = users.map((user) => ({
...user,
circles: [...user.circles],
}));
// Step 5: Recreate circles from startIndex
for (let i = startIndex - 1; i < totalStages; i++) {
console.log(`Recreating circles for stage ${i + 1}`);
let newUsers = users.map((user) => ({ ...user, circles: [] }));
// Create new circles
for (let j = 0; j < newUsers.length; j++) {
const circle = baseUsers[j].circles[i];
if (!circle) {
console.warn(`No base circle found for user ${baseUsers[j].user_name} at index ${i}`);
continue;
}
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);
}
// Handle "Empty" opponents
for (let j = 0; j < newUsers.length; j++) {
const user = newUsers[j];
const circle = user.circles[0];
if (circle.opponentGame.name.toLowerCase() === "empty") {
console.log(`User ${user.user_name} has an "Empty" opponent in circle ${circle.index_circle}`);
const sectorEmpty = circle.opponentGame.sector;
const changeSectorEmpty = cornerSectors.includes(sectorEmpty) ? 1 : -1;
let userNewOpponent = null;
let userNewOpponentIndex = -1;
// Find new opponent based on sector
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) {
console.log(`Assigning new opponent ${userNewOpponent.user_name} to user ${user.user_name}`);
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(
`No opponent found for user ${user.user_name} in circle ${circle.index_circle}`
);
}
}
}
// Add new circles to 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]);
}
}
}
// Step 6: Update users with finalNewUsers
for (let i = 0; i < users.length; i++) {
users[i].circles = finalNewUsers[i].circles;
}
// Step 7: Emit updated users
io.emit("allUsersUpdated", users);
console.log("adjustUsersAfterCornerSectorsUpdate completed successfully.");
} catch (error) {
console.error("Error in adjustUsersAfterCornerSectorsUpdate:", error);
}
}